0
votes

I was wondering whether the following setup would work for a small game:

Lets assume I have the following functions registered to Lua like so:

lua_register(L, "createTimer", createTimer);
lua_register(L, "getCondition", getCondition);
lua_register(L, "setAction", setAction);

Where: (leaving the type checking behind)

int createTimer(lua_State* L){
    string condition = lua_tostring(L, 1);
    string action = lua_tostring(L, 2);
    double timer = lua_tonumber(L, 3);
    double expiration = lua_tonumber(L, 4);

    addTimer(condition, action, timer, expiration); // adds the "timer" to a vector or something
 return 1;
}

Calling this function in lua by:

createTimer("getCondition=<5", "setAction(7,4,6)", 5, 20);

Can I then do the following(?):

// this function is called in the game-loop to loop through all timers in the vector
void checkTimers(){
    for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
        if(luaL_doString(L, *it->condition)){
            luaL_doString(L, *it->action)
        }
    }
}

Would this work? Would luaL_doString pass "getCondition=<5" to the lua state engine, where it will call the c++ function getCondition(), then see if it is =<5 and return true or false? And would the same go for luaL_doString(L, "setAction(7, 4, 6)"); ?

Moreover, would this be a suitable way to create timers by only accessing lua once (to create them) and let c++ handle the rest, only calling the c++ functions through lua and letting lua deal with logic only?

Thanks in advance.

2

2 Answers

1
votes

You may want to change the condition string to "return getCondition()<=5" otherwise the string chunk will not compile or run. Then check the boolean return value on the stack when the luaL_doString() returns successfully. Something like this:

// this function is called in the game-loop to loop through all timers in the vector
void checkTimers(){
    for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) {
        lua_settop(L, 0);
        if(luaL_doString(L, *it->condition) == 0 && lua_toboolean(1)){
            luaL_doString(L, *it->action);
        }
    }
}
0
votes

You cannot interrupt Lua while it is running. The best you can do is to set a flag and then handle the interruption at a safe time. The standalone interpreter uses this technique to handle user interrupts (control-C). This technique is also used in my lalarm library, which can be used to implement timer callbacks, though not at the high level you want.