Get Lua string from C -
i'm trying learn lua , how interface , c it. first attempt follows has been simplified include issue i'm seeing.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <linux/limits.h> /* path_max */ #include <unistd.h> #include <getopt.h> #include <lua.h> #include <lualib.h> #include <lauxlib.h> #define exitf exit(exit_failure) lua_state* lua; void stackdump(lua_state* lua) { int i, t; int top = lua_gettop(lua); (i = 1; <= top; i++) { t = lua_type(lua, i); switch (t) { case lua_tstring: printf("\"%s\"", lua_tostring(lua, i)); break; case lua_tboolean: printf(lua_toboolean(lua, i) ? "true" : "false"); case lua_tnumber: printf("%g", lua_tonumber(lua, i)); break; default: printf("%s", lua_typename(lua, t)); break; } if (i < top) printf(", "); } printf("\n"); } int main(int argc, char** argv) { int opt; char cfgfile[path_max]; cfgfile[0] = 0; lua = lual_newstate(); lual_openlibs(lua); stackdump(lua); while ((opt = getopt(argc, argv, "c:")) != -1) { switch (opt) { case 'c': strncpy(cfgfile, optarg, path_max); cfgfile[path_max - 1] = 0; break; } } if (cfgfile[0] == 0) { fprintf(stderr, "no cfg file specified\n"); return exit_failure; } printf("cfgfile = \"%s\"\n", cfgfile); if (lual_loadfile(lua, cfgfile) != lua_ok) { fprintf(stderr, "%s\n", lua_tostring(lua, -1)); lua_pop(lua, 1); lua_close(lua); return exit_failure; } stackdump(lua); lua_getglobal(lua, "program"); stackdump(lua); if (lua_isstring(lua, -1) == 0) { fprintf(stderr, "`program` should string\n"); lua_close(lua); return exit_failure; } char execarg0[256]; strncpy(execarg0, lua_tostring(lua, -1), 256); lua_pop(lua, 1); lua_close(lua); return exit_success; } lua script:
#!/usr/bin/env lua program = "echo" what i'm seeing when running is:
$ ./wrapper2 -c wrapper2.lua cfgfile = "wrapper2.lua" function function, nil `program` should string note empty line intentional; stackdump() tells stack empty @ point. seems call lua_getglobal(lua, "program") pushing nil on stack instead of string "echo". please me work out why i'm seeing this?
as side question: why there function pushed on stack (presumably lual_loadfile())? don't remember reading functions pushed on stack automatically.
lual_loadfile loads lua script not execute , not define global program. use lual_dofile instead.
lual_loadfile compiles lua script , leaves code lua function on stack.
lual_dofile calls lual_loadfile , calls function.
see manual entries lual_loadfile , lual_dofile.
Comments
Post a Comment