test.exe call addTest.lua and set the lua_testobj
to the table, and addTest.lua call testobj.dll,
but testobj.dll can not get the "lua_testobj"
error msg is
addTest.lua:9 attempt to index local 'testobj' (a userdata value)
test.exe
L = luaL_newstate(); // link lua lib luaL_openlibs(L); // addLuaCPath( L, "./clib/?.dll" ); // lua_pushlightuserdata(L, (void*)g_TestObj.get()); // g_TestObj is a global vars lua_setfield(L, LUA_REGISTRYINDEX, "lua_testobj"); // int err = 0; err = luaL_loadfile( L, "./lua/addTest.lua" ); if( err != LUA_OK ) printf("Failed to load addTest.lua![%s]", lua_tostring(L,-1)); err = lua_pcall( L, 0, 1, 0 ); if( err != LUA_OK ) printf("Failed to call addTest.lua![%s]", lua_tostring(L,-1));
the addtest.lua code is following
local luapath = package.path local cpath = package.cpath print(luapath) print(cpath) local testobj= require "testobj" testobj.addTest()
and the testobj.dll source code is following
static int laddTest(lua_State *L) { lua_getfield(L, LUA_REGISTRYINDEX, "lua_testobj"); return 1; } extern "C" int __declspec(dllexport) luaopen_testobj(lua_State *L) { luaL_Reg l[] = { { "addTest", laddTest }, { NULL, NULL }, }; luaL_checkversion(L); luaL_newlib(L,l); lua_getfield(L, LUA_REGISTRYINDEX, "lua_testobj"); CTestObj* pTestObj = static_cast<CTestObj*>( lua_touserdata(L,-1) ); return 1; }
I've modified the
luaopen_testobj
function, addlua_pop(L, 1);
before returnNow, it can correctly to obtain the value of pTestObj, no longer appear "addTest.lua:9 attempt to index local 'testobj' (a userdata value)" wrong.
But I don't know what's the meaning of the error message
It looks like
testobj.dll
did actually return yourlua_testobj
successfully because the error you're getting:indicates lua sees
testobj
as auserdata
. That's not where the problem is; the real issue is that you didn't associate any metatable with that userdata so lua can't really do anything with it when a script tries to use it.I've modified your
luaopen_testobj
to create and register a metatable for yourtestobj
:This should allow you to access
laddTest
usingtestobj:addTest()
from lua.laddtest
should check thattestobj
is indeed the userdata you passed in, for example: