luapage/lua.c
2021-05-03 14:51:05 +03:00

58 lines
No EOL
1.6 KiB
C

#include "ui.h"
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <luajit.h>
int lua_pcall_file(lua_State* L, const char* file) {
luaL_loadfile(L, file);
if (lua_pcall(L, 0, 0, 0) != 0) {
fprintf(stderr, "lua: script[%s]: error: %s\n", file, lua_tostring(L, -1));
return 1;
}
return 0;
}
int lua_create_c_function(lua_State* L, const char* name, lua_CFunction func) {
lua_pushcfunction(L, func);
lua_setglobal(L, name);
}
int lua_init_state(lua_State* L, struct application_state* state) {
int status;
luaL_openlibs(L); // unsafe
int pageview_append_tag(lua_State* L) {
const char* tag_type = luaL_checkstring(L, 1);
const char* tag_text = luaL_checkstring(L, 2);
switch (tag_type[0]) {
case 't': {
page_application_text_buffer_append_text(state, tag_text);
break;
}
default: {
return luaL_error(L, "ext_error: tried to create tag that does not exist");
}
}
return 0;
}
int pageview_set_content(lua_State* L) {
const char* new_content = luaL_checkstring(L, 1);
page_application_text_buffer_set_text(state, new_content);
}
lua_create_c_function(L, "__ext_pageview_append_tag", pageview_append_tag);
lua_create_c_function(L, "__ext_pageview_set_content", pageview_set_content);
status = lua_pcall_file(L, "corescripts/_global.lua");
if (status != 0) return 1;
status = lua_pcall_file(L, "pages/test.lua");
if (status != 0) return 2;
printf("lua: ready\n");
return 0;
}