0
\$\begingroup\$

For my game in C++ I'm using different objects (like player, enemy, et cetera) which will have to be controlled by a Lua script. My problem is that if I were to write a function in my player script, all my other scripts will have access to it as well, and I don't want that.

I can think of three basic solutions:

  • For every iteration clear the entire state and re-register everything
  • Determine out what functions a script registers and remove them
  • Have every gameobject running it's own Lua state

Is there a good way to do this, keeping runtime performance in mind?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ It might help if you provide some details about the kinds of functions you are talking about having access to. \$\endgroup\$
    – user1430
    Commented Jan 25, 2014 at 0:31
  • \$\begingroup\$ Why do you want to do this? Are you creating a multiplayer game and need to prohibit players from cheating? If not, why bother? \$\endgroup\$
    – Stephen
    Commented Jan 25, 2014 at 13:18
  • \$\begingroup\$ Is there a reason why you can't use the local keyword? According to this page, you should always use local unless another part of the program needs to access that particular variable/function. \$\endgroup\$
    – Lysol
    Commented Jan 26, 2014 at 5:41

1 Answer 1

2
\$\begingroup\$

You can give each script it's own Evironment. This is the table that is otherwise usually thought of as the global scope. With this, each function that you declare in your script will be confined to that script unless you expose and subsequently explicitly use a name to access the global table, e.g. _G.myfunc = function foo() end.

This is sometimes called "sandboxing," thought that term may be a bit misleading since it doesn't fully isolate the scripts.

See https://stackoverflow.com/questions/11013727/sandboxing-embedded-lua-in-5-2-set-envirenment-for-functions-from-lua-file for some code samples.

It's not necessarily a bad idea to use a separate coroutine (state) for each player object, though. This has advantages if you're trying to use more coroutines or a state machine inside the player object. A fully separated top-level lua_State is deinitely overkill.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .