Refactor loading of stdlib embedded modules

Author Mitja Felicijan <mitja.felicijan@gmail.com> 2025-08-06 12:00:43 +0200
Committer Mitja Felicijan <mitja.felicijan@gmail.com> 2025-08-06 12:00:43 +0200
Commit d2c6810f16fd4227e8a74e8590f82f1f50df3a98 (patch)
-rw-r--r-- main.c 36
1 files changed, 13 insertions, 23 deletions
diff --git a/main.c b/main.c
...
26
	return val;
26
	return val;
27
}
27
}
28
  
28
  
  
29
static int load_embedded_module(lua_State *L, const char* module_code, size_t code_len, const char* module_name) {
  
30
	if (luaL_loadbuffer(L, module_code, code_len, module_name) || lua_pcall(L, 0, 1, 0)) {
  
31
		fprintf(stderr, "Error loading %s: %s\n", module_name, lua_tostring(L, -1));
  
32
		return 0;
  
33
	}
  
34
	lua_setglobal(L, module_name);
  
35
	return 1;
  
36
}
  
37
  
29
static int l_open_window(lua_State *L) {
38
static int l_open_window(lua_State *L) {
30
	int width = luaL_checknumber(L, 1);
39
	int width = luaL_checknumber(L, 1);
31
	int height = luaL_checknumber(L, 2);
40
	int height = luaL_checknumber(L, 2);
...
98
	lua_register(L, "draw_fps", l_draw_fps);
107
	lua_register(L, "draw_fps", l_draw_fps);
99
	lua_register(L, "clear_window", l_clear_window);
108
	lua_register(L, "clear_window", l_clear_window);
100
  
109
  
101
	// Embedding JSON module.
110
	// Loading embeded modules into Lua state.
102
	if (luaL_loadbuffer(L, json, json_len, "json") || lua_pcall(L, 0, 1, 0)) {
111
	if (!load_embedded_module(L, json, json_len, "json")) return 1;
103
		fprintf(stderr, "Error loading json.lua: %s\n", lua_tostring(L, -1));
112
	if (!load_embedded_module(L, color, color_len, "color")) return 1;
104
		lua_close(L);
113
	if (!load_embedded_module(L, tilemap, tilemap_len, "tilemap")) return 1;
105
		return 1;
  
106
	}
  
107
	lua_setglobal(L, "json");
  
108
  
  
109
	// Embedding color module.
  
110
	if (luaL_loadbuffer(L, color, color_len, "color") || lua_pcall(L, 0, 1, 0)) {
  
111
		fprintf(stderr, "Error loading color.lua: %s\n", lua_tostring(L, -1));
  
112
		lua_close(L);
  
113
		return 1;
  
114
	}
  
115
	lua_setglobal(L, "color");
  
116
  
  
117
	// Embedding tilemap module.
  
118
	if (luaL_loadbuffer(L, tilemap, tilemap_len, "tilemap") || lua_pcall(L, 0, 1, 0)) {
  
119
		fprintf(stderr, "Error loading tilemap.lua: %s\n", lua_tostring(L, -1));
  
120
		lua_close(L);
  
121
		return 1;
  
122
	}
  
123
	lua_setglobal(L, "tilemap");
  
124
  
114
  
125
	// Interpreting and running input file Lua script.
115
	// Interpreting and running input file Lua script.
126
	if (luaL_loadfile(L, IN_FILE) || lua_pcall(L, 0, 0, 0)) {
116
	if (luaL_loadfile(L, IN_FILE) || lua_pcall(L, 0, 0, 0)) {
...