lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


于 2012-8-25 19:12, Gao Xianchao 写道:

It seems that lua_pcallk() can not be used in main thread of a lua_State?

btw, lua_resume() works


test code:


==lua script test.txt==
function dotest()
local a = mytest()
error("err from lua a="..a)
end


C++ code:


CluatestDlg::OnInitDialog()
{
......
l = luaL_newstate();
luaL_openlibs(l);
lua_register(l, "mytest", lua_mytest);
}


static int lua_mytest_con_func(lua_State* ls)
{
return 0;
}


void CluatestDlg::OnBnClickedButton3()
{
if(luaL_dofile(l, "test.txt")) return;
lua_getglobal(l, "dotest");


int ret = lua_pcallk(l, 0, 0, 0, 0, lua_mytest_con_func);
if(ret != 0)
{
const char* err = luaL_checkstring(l, -1);
//err : attempt to yield from outside a coroutine
TRACE(err);
}
}


//lua_resume works fine
void CluatestDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
if(luaL_dofile(l, "test.txt")) return;
    lua_getglobal(l, "dotest");


int ret = lua_resume(l, NULL, 0);
if((ret!=LUA_OK) && (ret!=LUA_YIELD))
{
const char* err = luaL_checkstring(l, -1);
TRACE(err);
return;
}


int b = ret + 1;
}


​​
it's nothing wrong with lua_pcallk.
you just can't yield from the main thread.

Lua's `thread' is asymmetric, i.e. the so called `collaborative multithreading',
which is actually just a programming model.
it is not true multithreading.

the **asymmetric** nature means we need two different APIs to deal with `thread'.
i.e. the `resume' and 'yield'.
the **asymmetric** also means there must be one and the only `main thread', which
behaves differently from all other threads.

so you must first understand the `threading' model of Lua, then use the right API.