Accessing Lua Tables from C
- Tables in Lua are accessed through the stack
- Generally a Lua file is loaded and then the stack accessed
The rules for accessing a table are as follows:
1\. The assumption is that the table is global in Lua and can be accessed using
lua_getglobal(L, tablename);
2\. lua_getglobal will cause the table to be put on the stack
3\. test that the top element on the stack is a table
4\. push a table key onto the stack, ends up on the stack top
5\. do a lua_gettable which will take the key and access the table
6\. do a lua_pop of the top element to remove the key
7\. do the same thing for other keys
```
_An Example of accessing a table in Lua through the Stack_
```
#include
#include
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
void load (lua_State *L, const char *fname, int *red, int *green, int *blue);
int getcolorfield(lua_State *L, const char *key);
#define MAX_COLOR 255
int main(void) {
lua_State *L = luaL_newstate(); /* opens Lua */
luaL_openlibs(L); /* opens the standard libraries */
char filename[] = "C:/Lua C and C++/workspace/configTable.lua";
int red = 0;
int green = 0;
int blue = 0;
load(L, filename, &red, &green, &blue);
printf("red is %d\n", red);
printf("green is %d\n", green);
printf("blue is %d", blue);
return 0;
}
void load (lua_State *L, const char *fname, int *red, int *green, int *blue) {
if (luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0)) {
luaL_error(L, "cannot run config file: %s", lua_tostring(L, -1));
}
lua_getglobal(L, "background");
if (!lua_istable(L, -1)) {
luaL_error(L, "'background' is not a table\n");
}
int r = getcolorfield(L, "r");
int g = getcolorfield(L, "g");
int b = getcolorfield(L, "b");
*red = r;
*green = g;
*blue = b;
}
int getcolorfield(lua_State *L, const char *key) {
int result;
lua_pushstring(L, key);
lua_gettable(L, -2);
if (!lua_isnumber(L, -1)) {
luaL_error(L, "invalid component in background color");
}
result = (int)(lua_tonumber(L, -1) * MAX_COLOR);
lua_pop(L, 1);
return result;
}
```
_The Lua file with the table_
```
background = {r=0.30, g=0.10, b=0}
BLUE = {r=0, g=0, b=1.0}
background1 = BLUE
```