Advertisement

LUA - Retrieving Table Var

Started by July 09, 2004 01:09 PM
3 comments, last by Monder 20 years, 4 months ago
I have this simple LUA code:
Shader = { Label, SHandler, SType, Qual };
Shader.Label	 = "Proto Vertex Shader - Difuse";
Shader.Qual      = 100;
I don't only define Label, i define all the other variables. My problem now is retrieving this information back into C++ I have this code, and it doesnt seem to be working:

	int Qual = lua_getglobal(L, "Shader.Qual"); 
	temp = (int)lua_tonumber(L, 1); 
	lua_pop(L, 1);
What could be wrong?
"Shader.Qual" isn't a global variable. "Shader" is. "Qual" is a key in that table. You'll need to get the "Shader" global, push the string "Qual" onto the stack, and use gettable to retrieve that value.

BTW, your lua code doesn't do what you think it does. There's no need to "reserve" slots in a table at creation time, which it looks like you're trying to do. What that first line does is set up a table with four integer keys (1,2,3, and 4), each with a value equal to a global variable that (I'm assuming) is nil at that point, thus no values are getting set. Just do "Shader = {}".
Advertisement
Hey just a note...if you were using luabind you could do something like this to get at the value:

#include <luabind/luabind.hpp>#include <luabind/object.hpp>using namespace luabind;lua_State* L;object shader = get_globals(L)["Shader"];int Qual = object_cast<int>(shader["Qual"]);string Label = object_cast<string>(shader["Label"]);


...and so on. It just kind of a nice way to hide the messy details of the Lua stack.
Quote: Original post by Sneftel
"Shader.Qual" isn't a global variable. "Shader" is. "Qual" is a key in that table. You'll need to get the "Shader" global, push the string "Qual" onto the stack, and use gettable to retrieve that value.


Any chance you could provide some code? Im a bit lost in the documentation...
lua_pushstring(state, "Shader");lua_gettable(state, LUA_GLOBALSINDEX);lua_pushstring(state, "Qual");lua_gettable(state, -2);int Qual = lua_tonumber(state, -1);lua_pop(state, 2);


First you grab the shader table from the global environment (which is itself a table at the index LUA_GLOBALSINDEX) and then you use gettable to access the Qual variable from that table.

[edit]If you're not gonna use anything like luaBind define some macros (or something more sophisticated) to do this all for you, it's far easier[/edit]

This topic is closed to new replies.

Advertisement