0

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;
}

エラーが表示されます: userdata 値にインデックスを付けようとしてい
ます lua_topointer() から lua のオブジェクトにアクセスする方法は?
lua オブジェクトを C に格納し、C から呼び出します。

4

2 に答える 2

3

lua_topointerlua オブジェクトに戻すことができないため、使用しないでください。オブジェクトをレジストリに保存し、そのレジストリ インデックスを渡します。

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-09T09:39:28.520 に答える
1

lua_topointerそのタスクには使用したくありません。実際、唯一の妥当な使用法lua_topointerは、デバッグ目的 (ロギングなど) です。

tableと同様aに、そのフィールドの 1 つにアクセスするには を使用する必要があります。もちろん、そのタスクにポインターを渡すことはできませんが、代わりにスタック インデックスを使用できます。lua_gettablelua_getfieldvoid*processObj

于 2013-01-09T09:33:17.340 に答える