77 lines
1.5 KiB
C
77 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
#include <lauxlib.h>
|
|
#include <lua.h>
|
|
#include <lualib.h>
|
|
|
|
static int traceback(lua_State *L) {
|
|
if (!lua_isstring(L, 1)) {
|
|
if (lua_isnoneornil(L, 1) || !luaL_callmeta(L, 1, "__tostring") || !lua_isstring(L, -1)) {
|
|
return 1;
|
|
}
|
|
|
|
lua_remove(L, 1);
|
|
}
|
|
|
|
luaL_traceback(L, L, lua_tostring(L, 1), 1);
|
|
|
|
return 1;
|
|
}
|
|
|
|
static void report(lua_State *L) {
|
|
const char *msg = lua_tostring(L, -1);
|
|
if (!msg) {
|
|
msg = "(error object is not a string)";
|
|
}
|
|
|
|
fprintf(stderr, "[ERROR] hate-no-d: %s\n", msg);
|
|
fflush(stderr);
|
|
lua_pop(L, 1);
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if (argc < 2) {
|
|
fprintf(stderr, "Usage: %s <file-path> [args...]\n", argv[0]);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
const char *file_path = argv[1];
|
|
|
|
lua_State *L = luaL_newstate();
|
|
if (!L) {
|
|
fprintf(stderr, "[ERROR] hate-no-d: cannot create Lua state\n");
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
luaL_openlibs(L);
|
|
|
|
lua_createtable(L, argc - 1, 1);
|
|
for (int i = 0; i < argc; i++) {
|
|
lua_pushstring(L, argv[i]);
|
|
lua_rawseti(L, -2, i - 1);
|
|
}
|
|
lua_setglobal(L, "arg");
|
|
|
|
int status = luaL_loadfile(L, file_path);
|
|
if (status != LUA_OK) {
|
|
report(L);
|
|
lua_close(L);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
lua_pushcfunction(L, traceback);
|
|
lua_insert(L, -2);
|
|
|
|
status = lua_pcall(L, 0, 0, -2);
|
|
if (status != LUA_OK) {
|
|
report(L);
|
|
lua_close(L);
|
|
return EXIT_FAILURE;
|
|
}
|
|
|
|
lua_pop(L, 1);
|
|
lua_close(L);
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|