Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include "lua5.2/lua.h"
- #include "lua5.2/lualib.h"
- #include "lua5.2/lauxlib.h"
- // Our main function
- void my_main(lua_State*);
- // Vector class
- void vector(lua_State*);
- // Error handling
- void bail(lua_State*, const char*);
- int main() {
- // Init Lua
- lua_State* Lua = luaL_newstate();
- // Call Lua base library
- luaopen_base(Lua);
- // Call Lua auxiliary library
- luaL_openlibs(Lua);
- // Load Vector class
- vector(Lua);
- // Load our main function
- my_main(Lua);
- // Clean up Lua state
- lua_close(Lua);
- return 0;
- }
- // Our main function
- void my_main(lua_State* L) {
- int state =
- luaL_dostring(L,
- "v = Vector:from_table({1, 2, 3, 4});"
- "assert(#v == 4);"
- "assert(v[1] == 1);");
- if (state != LUA_OK) {
- bail(L, "Failed to load main block\n");
- }
- }
- // Vector class
- void vector(lua_State* L) {
- int state =
- luaL_dostring(L,
- "Vector = {};"
- "Vector.__index = Vector;"
- "function Vector:new(size);"
- " local self = {};"
- " for i = 1, size do;"
- " table.insert(self, 0);"
- " end;"
- " setmetatable(self, Vector);"
- " return self;"
- "end;"
- "function Vector:from_table(t);"
- " local v = Vector:new(#t);"
- " for i = 1, #t do;"
- " v[i] = t[i];"
- " end;"
- " return v;"
- "end;");
- if (state != LUA_OK) {
- bail(L, "Failed to load Vector class\n");
- }
- }
- void bail(lua_State* L, const char* msg) {
- fprintf(stderr, "ERROR: %s: %s\n",
- msg, lua_tostring(L, -1));
- lua_close(L);
- exit(EXIT_FAILURE);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement