2

In Lua Code

Test = {}
function Test:new()
  local obj = {}
  setmetatable(obj, self)
  self.__index = self
  return obj
end
local a = Test:new()
a.ID = "abc123"
callCfunc(a)

In C Code

int callCfunc(lua_State * l)
{
   void* obj = lua_topointer(l, 1);            //I hope get lua's a variable
   lua_pushlightuserdata(l, obj);   
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, 1);        //I hoe get the value "abc123"
   ...
   return 0;
}

But My C result is

id = null

Why? How to modify code to work fine ?
PS: I don't hope create C Test Class mapping to lua

==== update1 ====
In addition, I have added the test code to confirm correct incoming parameters.

int callCfunc(lua_State * l)
{
   std::string typeName = lua_typename(l, lua_type(l, 1));    // the typeName=="table"
   void* obj = lua_topointer(l, 1);            //I hope get lua's a variable
   lua_pushlightuserdata(l, obj);   
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, 1);        //I hoe get the value "abc123"
   ...
   return 0;
}

the result

typeName == "table" 

so incoming parameter type is Correct

3
  • Aren't objects indexed from 0? Should not all the 1s be zeroes instead? Commented Jan 8, 2013 at 5:55
  • You may like to accept some of your answers - you'll get more responses. 0% accept is less than acceptable :-) Commented Jan 8, 2013 at 7:23
  • In addition, I have added the test code to confirm correct incoming parameters. std::string typeName = lua_typename(l, lua_type(l, 1)); the result typeName == "table" so incoming parameter type is Correct. Commented Jan 8, 2013 at 7:34

2 Answers 2

3

I found the reason
Correct c code should is ...
In C Code

int callCfunc(lua_State * l)
{
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, -1);        //-1
   ...
   return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to close the question? I don't find the close menu.
use lua_istable() to check the input parameter is a table - pgl.yoyo.org/luai/i/lua_istable. To close the question just accept an answer - if your's then you'll have to wait a while I think.
0

Maybe this - haven't tested sorry - don't have a compiler handy

Input is the table from lua on top of the stack, so getfield(l,1, "ID") should get the field ID from the table at the top of the stack - which in this case is your input table. It then pushes the result to the top of the stack

int callCfunc(lua_State * l)
{
   lua_getfield(l, 1, "ID");
   std::string id = lua_tostring(l, 1);        //I hoe get the value "abc123"
   ...
   return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.