在Lua代码中
Test = {}
function Test:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
local a = Test:new()
a.ID = "abc123"
callCfunc(a)在C代码中
int callCfunc(lua_State* l)
{
SetLuaState(l);
void* lua_obj = lua_topointer(l, 1); //I hope get lua's a variable
processObj(lua_obj);
...
return 0;
}
int processObj(void *lua_obj)
{
lua_State* l = GetLuaState();
lua_pushlightuserdata(l, lua_obj); //access lua table obj
int top = lua_gettop(l);
lua_getfield(l, top, "ID"); //ERROR: attempt to index a userdata value
std::string id = lua_tostring(l, -1); //I hoe get the value "abc123"
...
return 0;
}我收到错误消息:尝试为用户数据值建立索引
如何从lua_topointer()访问lua的对象?
将lua对象存储在C中,然后从C中调用它。
发布于 2013-01-09 17:39:29
您不应该使用lua_topointer,因为您无法将其转换回lua对象,将对象存储在注册表中,并传递它的注册表索引
int callCfunc(lua_State* L)
{
lua_pushvalue(L, 1);//push arg #1 onto the stack
int r = luaL_ref(L, LUA_REGISTRYINDEX);//stores reference to your object(and pops it from the stask)
processObj(r);
luaL_unref(L, LUA_REGISTRYINDEX, r); // removes object reference from the registry
...
int processObj(int lua_obj_ref)
{
lua_State* L = GetLuaState();
lua_rawgeti(L, LUA_REGISTRYINDEX, lua_obj_ref);//retrieves your object from registry (to the stack top)
...发布于 2013-01-09 17:33:17
您不希望使用lua_topointer来完成该任务。事实上,lua_topointer的唯一合理用法是用于调试目的(如日志记录)。
因为a是一个表,所以您需要使用lua_gettable来访问它的一个字段,或者甚至更简单地使用lua_getfield。当然,您不能将void*指针传递给该任务的processObj,但您可以使用堆栈索引。
https://stackoverflow.com/questions/14230821
复制相似问题