Gergely Tarkó
Gergely Tarkó

Reputation: 157

C++ multiple Lua states

I want to use the same lua file for multiple game objects

The lua file:

function onUpdate()
    if Input.isKeyDown(Keys.d) then
        actor.x = actor.x + 0.1
    end

    if Input.isKeyDown(Keys.a) then
        actor.x = actor.x - 0.1
    end

    if Input.isKeyDown(Keys.w) then
        actor.y = actor.y + 0.1
    end

    if Input.isKeyDown(Keys.s) then
        actor.y = actor.y - 0.1
    end
end

Question

Is it a good practice to have a Lua State for each object or should i use the same state for the same file and update the "actor" global variable before the game object calls the script (I want to avoid using tables because i would have to use the table name before the variables and function calls) (I don't know if there is any other solution... I am new to lua)

Upvotes: 2

Views: 1861

Answers (1)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7046

While it is nice that you can have many Lua states within a single program, keep in mind that each of them does take up some memory. If there's a good reason why you should keep two environments completely separate, like security concearns, or totally unrelated subsystems that may or may not be needed at the same time, then it's certainly worth it.

Otherwise, it's usually better and more manageable to have a single Lua state.


If you need strong separation between different blocks of logic, Lua has you covered:

Coroutines

If you need to have several blocks of logic that you want to pause and resume later on, you can simply wrap them up in coroutines. This can easily be done from C as well, and allows you to do most of what you could do with different Lua states.

Environments

While these work somewhat differently before and after Lua 5.2, the basic idea is the same: you can change what "global" variables are visible to a section of your code, even using metatables to access other data or generate it on the fly.


With those two, you should really not have much need for separate Lua states in a game. One exception to this rule would obviously be multi-threading; you shouldn't have more than one thread with access to the same Lua state unless you use some sort of locking mechanism, so it would make sense to have one state per thread and set up a way for them to communicate from within C.

Upvotes: 0

Related Questions