Reputation: 109
I got 2 functions that register Lua table and method in C++:
void LuaScriptInterface::registerTable(const std::string& tableName)
{
// _G[tableName] = {}
lua_newtable(luaState);
lua_setglobal(luaState, tableName.c_str());
}
void LuaScriptInterface::registerMethod(const std::string& globalName, const std::string& methodName, lua_CFunction func)
{
// globalName.methodName = func
lua_getglobal(luaState, globalName.c_str());
lua_pushcfunction(luaState, func);
lua_setfield(luaState, -2, methodName.c_str());
// pop globalName
lua_pop(luaState, 1);
}
It registers some methods:
registerTable("Game");
// Game.getHouses()
registerMethod("Game", "getHouses", LuaScriptInterface::luaGameGetHouses);
Then I call in Lua:
local param = "print( Game.getHouses() )"
pcall(loadstring(param))
I got problem with param. Calls and results:
1. print(Game.getHouses())
2. print(Game['getHouses']())
3. print( Game.getHouses() ) -- added spaces
4. print( Game['getHouses']() ) -- added spaces
5. local var = Game.getHouses() print(#var)
6. local var = Game['getHouses']() print(#var)
7. local var = #Game.getHouses() print(var)
8. local var = #Game['getHouses']() print(var)
9. local var = # Game.getHouses() print(var) -- added space
Results:
1. attempt to call a nil value
2. table: 0x4351fdd0
3. table: 0x42ce6b88
4. table: 0x426513c0
5. 1010
6. 1010
7. attempt to call a nil value
8. 1010
9. 1010
Can anyone tell me a reason, why it does not work in loadstring/pcall?
Can I make it work in loadstring/pcall somehow?
EDIT:
After 2 hours of debugging. I found out, that client that I use to communicate with server - that executes LUA - does some regex on string that I send (I still don't know why, but it's not LUA related) :)
Upvotes: 3
Views: 171
Reputation: 881
The problem you tried to represent is that someTable.key
gives a different result than someTable["key"]
but this cant be possible:
But it's so common to use string constants as keys there's a special shortcut syntax for it:
> t = {} > t.foo = 123 -- same as t["foo"] (but not t[foo], which would use the variable foo as the key) > = t.foo 123 > = t["foo"] 123
The shortcut syntax is only valid if the string consists of underscores, letters, and numbers, but shouldn't start with a number. (http://lua-users.org/wiki/TablesTutorial)
Supported by the fact that it works when not used in loadstring
, I suspect that your problem is rather with Player(cid)
player:getId()
or "player:getPosition()"
. Important to notice that you are accessing player at two different times. 1. Directly as player:getId()
and 2. though loadstring / pcall
. The last possibility would be the Player(cid)
. One of them is propably not correctly initialized / declared.
I think because of different test conditions your second attempt local param = "print( #Game['getHouses']() )"
worked.
Upvotes: 6