Created
August 24, 2014 20:10
-
-
Save markuman/77806e93cf10a0690a5d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <lua.h> | |
#include <lualib.h> | |
#include <lauxlib.h> | |
int main() { | |
// open lua stack | |
int result; | |
lua_State *L = luaL_newstate(); | |
luaL_openlibs(L); | |
// a = {7, 6, 8, 3, 4, 1} | |
result = luaL_loadfile(L, "array.lua") || lua_pcall(L, 0, 0, 0); | |
if (result){ | |
fprintf(stderr, "Fehler beim Laden des Skripts: %s!\n", lua_tostring(L, -1)); | |
} | |
// put variable "a" from lua script into the stack | |
lua_getglobal(L, "a"); | |
// length of array | |
lua_len(L, 1); | |
int len = lua_tonumber(L, -1); | |
lua_pop(L, 1); // pop the output | |
printf("%d\n",len); //debug info | |
// lua_next() always expects for the previous key to be on the top | |
// of the stack. When you begin the loop, there is no previous key, so it expects nil | |
lua_pushnil(L); | |
// prealloc array | |
// double a[6] = {}; | |
double *a = (double*)malloc(len*sizeof(double)); | |
// get values from "a" array in lua | |
for(int n = 0; n < len; n++) { | |
lua_next( L, -2); | |
a[n] = lua_tonumber(L,-1); | |
printf("%f\n", a[n]); | |
lua_pop( L, 1 ); | |
} | |
// Close the Lua state | |
lua_close(L); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment