3

In my script I've got this global variable:

name = "Stabilizer"

And, I'm trying to fetch this variable in c++, like so:

char* CeScript::GetGlobalString(char* pName)
{
    luaL_loadstring(L, m_sScript.c_str());

    lua_getglobal(L, pName);

    return (char*)lua_tostring(L, -1);
}
....
char* _name = pScript->GetGlobalString("name");

But, lua_tostring returns a null ptr, suggesting that the global variable could not be found.

What could be the issue? Thank you.

Miguel P
  • 1,262
  • 6
  • 23
  • 48

1 Answers1

6

The loadstring just compiles the string into a Lua chunk, but to exec the chunk you have to call lua_pcall. Do that just after the loadstring, or assign it to a global or ref in registry if you need to pcall it repeatedly.

For code samples see other SO posts for keywords "luaL_loadstring lua_pcall" such as LUA_MULTRET not working as expected and c++ lua error on setting global variable.

Community
  • 1
  • 1
Oliver
  • 27,510
  • 9
  • 72
  • 103