1

Everywhere I looked, I saw that the best practice for running lua scripts from many C threads is to have a different lua_State for each thread. Going from this point, be the following script:

local var1
local var2
-- etc.

function onClick(x, y)
-- Process mouse click
end

function onKey(k)
-- Process key stroke
end

-- Do some stuff
while(true) do
-- Do some stuff
end

where onClick and onKey are callback functions called by a Win32 application. These functions are called each one by one C thread. Each one of these have it's own lua_State. Therefore, there is a total of 3 C threads (and 3 lua_States): one for each of the above functions, and the last one for running everything that is not a function (while loop and stuff). So, since Lua can only sees what's in script after lua_dofile and lua_dofile executes everything there is, how can those functions be called without the whole script being executed? I just want one thread to be stuck in the infinite loop; the other ones must wait from the callback functions.

6
  • 3
    You can't. Move your while loop into a function, and have your C code call it. Commented Nov 14, 2016 at 19:33
  • Thanks, that worked fine. Now, how can I communicate betweet the threads, so that local variables altered by one could see by another? Commented Nov 14, 2016 at 21:56
  • 1
    You can't, at least not in Lua directly. lua_states are completely separate from each other. You'll need a C API to do sharing, message passing, or whatever you need. Commented Nov 14, 2016 at 22:00
  • Any recommended API? P.S: I don't get the purpose of lua_newthread. It's supposed to do that exactly what I need: share the same global variables of the main lua_state with the child states. Problem is its behavior is crazy. Commented Nov 14, 2016 at 22:13
  • 3
    lua_newthread creates new coroutines, not OS threads. Commented Nov 15, 2016 at 3:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.