|
| 1 | +#include <lua.h> |
| 2 | +#include <lualib.h> |
| 3 | +#include <lauxlib.h> |
| 4 | +#include <stdio.h> |
| 5 | + |
| 6 | +#include "moonc.h" // the CLI script |
| 7 | + |
| 8 | +// from moonscript.c |
| 9 | +extern int luaopen_moonscript(lua_State *l); |
| 10 | + |
| 11 | +// from lfs.c |
| 12 | +extern int luaopen_lfs(lua_State *l); |
| 13 | + |
| 14 | +int main(int argc, char **argv) { |
| 15 | + lua_State *l = luaL_newstate(); |
| 16 | + luaL_openlibs(l); |
| 17 | + |
| 18 | + // Load moonscript (this also loads lpeg and argparse) |
| 19 | + luaopen_moonscript(l); |
| 20 | + lua_pop(l, 1); |
| 21 | + |
| 22 | + // Load luafilesystem and register it in package.loaded |
| 23 | + int nresults = luaopen_lfs(l); |
| 24 | + if (nresults > 0) { |
| 25 | + lua_getglobal(l, "package"); |
| 26 | + lua_getfield(l, -1, "loaded"); |
| 27 | + lua_pushvalue(l, -3); // push lfs table |
| 28 | + lua_setfield(l, -2, "lfs"); |
| 29 | + lua_pop(l, 2); // pop loaded, package |
| 30 | + } |
| 31 | + lua_pop(l, nresults); |
| 32 | + |
| 33 | + // Set up arg table |
| 34 | + lua_newtable(l); |
| 35 | + lua_pushstring(l, "moonc"); |
| 36 | + lua_rawseti(l, -2, -1); |
| 37 | + for (int i = 0; i < argc; i++) { |
| 38 | + lua_pushstring(l, argv[i]); |
| 39 | + lua_rawseti(l, -2, i); |
| 40 | + } |
| 41 | + lua_setglobal(l, "arg"); |
| 42 | + |
| 43 | + // Load and execute the moonc CLI script |
| 44 | + if (luaL_loadbuffer(l, (const char *)moonc_lua, moonc_lua_len, "moonc") != 0) { |
| 45 | + fprintf(stderr, "Failed to load moonc: %s\n", lua_tostring(l, -1)); |
| 46 | + return 1; |
| 47 | + } |
| 48 | + if (lua_pcall(l, 0, 0, 0) != 0) { |
| 49 | + fprintf(stderr, "Error: %s\n", lua_tostring(l, -1)); |
| 50 | + return 1; |
| 51 | + } |
| 52 | + |
| 53 | + lua_close(l); |
| 54 | + return 0; |
| 55 | +} |
0 commit comments