The following code uses luabind for lua coroutine Testing
1: void ScriptManagedChannel: OnServiceInitialize ()
2 :{
3: try
4 :{
5: mThread = lua_newthread (GScriptScriptContext-> GetVM ());
6:
7: luabind: resume_function <void> (mThread, "ScriptMain", this );
8:
9: Resume ();
10 :}
11: catch (std: exception & e)
12 :{
13: const char * ErrorMsg = lua_tostring (GScriptScriptContext-> GetVM (),-1 );
14: printf ("% s \ n", e. what ());
15 :}
16:
17:
18 :}
19:
20: void ScriptManagedChannel: Resume ()
21 :{
22: luabind: resume <void> (mThread );
23 :}
24:
25: void ScriptManagedChannel: StopTest ()
26 :{
27: lua_yield (mThread, 0 );
28 :}
29:
30:
In the code, the mThread type is lua_State *.
GScriptScriptContext-> GetVM () is the lua_State loaded with code *
StopTest is the definition of the function registered as a ScriptManagedChannel class member to lua.
Next, let's look at the lua test code:
1: function ScriptMain (Channel)
2:
3:
4: for I = 1, 5 do
5:
6: print ("done", I)
7:
8: Channel: StopTest ()
9:
10:
11:
12: end
13: end
At the beginning, when testing the code, there was a hand error in lua, causing the assert to pop up when the C ++ code runs to the 7th line.
Location: luabind-0.9.1 \ luabind \ detail \ call_function.hpp line 264th, corresponding to the following code line 13th
1 :~ Proxy_function_void_caller ()
2 :{
3: if (m_called) return;
4:
5: m_called = true;
6: lua_State * L = m_state;
7:
8: int top = lua_gettop (L );
9:
10: push_args_from_tuple <1 >:apply (L, m_args );
11: if (m_fun (L, boost: tuples: length <Tuple >:: value, 0 ))
12 :{
13: assert (lua_gettop (L) = top-m_params + 1 );
14:
15: NO_EXCEPTIONS
16: throw luabind: error (L );
17: # else
18: error_callback_fun e = get_error_callback ();
19: if (e) e (L );
20:
21: assert (0 & "the lua function threw an error and exceptions are disabled ."
22: "If you want to handle the error you can use luabind: set_error_callback ()");
23: std: terminate ();
24: # endif
25 :}
26: // pops the return values from the function call
27: stack_pop pop (L, lua_gettop (L)-top + m_params );
28 :}
The Code In line 11 calls lua_resume and returns a running error. However, it is blocked by the assert of line 13 and cannot be caught by the outside because the exception is thrown through line 11.
Therefore, try to comment out 13th rows and test again. After lua throws an error, capture the error message returned by the coroutine function resume at the top of the stack. Solve the problem.
For lua coroutine, there is not much information on the Internet. Here is a detailed code
I am wondering if it is necessary to pass in the newthread state when the code is in dofile or dobuffer? What will happen if the original state is passed in?
You are welcome to discuss this experience.
From the treasure Building