Next: 5.4 Calling Lua Functions Up: 5 The Application Program Previous: 5.2 Converting Values between

5.3 Manipulating Lua Objects

To read the value of any global Lua variable, one can use the function:

lua_Object     lua_getglobal            (char *varname);
As in Lua, if the value of the global is nil, the "getglobal" fallback is called.

To store a value previously pushed onto the stack in a global variable, there is the function:

void           lua_storeglobal          (char *varname);

Tables can also be manipulated via the API. The function

lua_Object     lua_getsubscript         (void);
expects on the stack a table and an index, and returns the contents of the table at that index. As in Lua, if the first object is not a table, or the index is not present in the table, the correspondent fallback is called.

To store a value in an index, the program must push onto the stack the table, the index, and the value, and then call the function:

void lua_storesubscript (void);
Again, the correspondent fallback is called if needed.

Finally, the function

lua_Object     lua_createtable          (void);
creates a new table.

Please Notice: Most functions from the Lua library receive parameters through the stack. Because other functions also use the stack, it is important that these parameters be pushed just before the correspondent call, without intermediate calls to the Lua library. For instance, suppose the user wants the value of a[i] . A simplistic solution would be:

  /* Warning: WRONG CODE */
  lua_Object result;
  lua_pushobject(lua_getglobal("a"));  /* push table */
  lua_pushobject(lua_getglobal("i"));  /* push index */
  result = lua_getsubscript();
However, the call lua_getglobal("i") modifies the stack, and invalidates the previous pushed value. A correct solution could be:
  lua_Object result;
  lua_Object index = lua_getglobal("i");
  lua_pushobject(lua_getglobal("a"));  /* push table */
  lua_pushobject(index);               /* push index */
  result = lua_getsubscript();


Next: 5.4 Calling Lua Functions Up: 5 The Application Program Previous: 5.2 Converting Values between