# How should I organize Lua scripts so that some entities do not have access to functions they shouldn't?

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?

• It might help if you provide some details about the kinds of functions you are talking about having access to. – user1430 Jan 25 '14 at 0:31
• Why do you want to do this? Are you creating a multiplayer game and need to prohibit players from cheating? If not, why bother? – Stephen Jan 25 '14 at 13:18
• 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. – Lysol Jan 26 '14 at 5:41

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.
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.