Advertisement
cwchen

Call Lua from File

Jan 18th, 2017
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "lua5.2/lua.h"
  4. #include "lua5.2/lualib.h"
  5. #include "lua5.2/lauxlib.h"
  6.  
  7. // Error handling
  8. void bail(lua_State*, const char*);
  9.  
  10. int main() {
  11.   // Init Lua
  12.   lua_State* Lua = luaL_newstate();
  13.  
  14.   // Call Lua base library
  15.   luaopen_base(Lua);
  16.  
  17.   // Call Lua auxiliary library
  18.   luaL_openlibs(Lua);
  19.  
  20.   // Main block
  21.   int state =
  22.     luaL_dostring(Lua,
  23.                   "Vector = require \"Vector\";"
  24.                   "v = Vector:from_table({1, 2, 3, 4});"
  25.                   "v = v + 1;"
  26.                   "assert(#v == 4);"
  27.                   "assert(v[1] == 2);");
  28.   if (state != LUA_OK) {
  29.     bail(Lua, "failed to load Lua statement");
  30.   }
  31.  
  32.   lua_close(Lua);
  33.  
  34.   return 0;
  35. }
  36.  
  37. void bail(lua_State* L, const char* msg) {
  38.   fprintf(stderr, "ERROR: %s: %s\n",
  39.           msg, lua_tostring(L, -1));
  40.   lua_close(L);
  41.   exit(EXIT_FAILURE);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement