Skip to content
This repository was archived by the owner on Jun 9, 2023. It is now read-only.

Commit 0659cb5

Browse files
authored
Create helper.hpp
1 parent 143d1d0 commit 0659cb5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

helper.hpp

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#pragma once
2+
3+
template<typename T>
4+
constexpr inline void set_userdata(lua_State* L, T* element) {
5+
*static_cast<T**>(lua_newuserdata(L, sizeof(T*))) = element;
6+
}
7+
8+
template<typename T>
9+
constexpr inline T* to_class_ptr(lua_State* L, int idx) {
10+
return *static_cast<T**>(lua_touserdata(L, idx));
11+
}
12+
13+
void set_type(lua_State* L, const char* type_name) {
14+
lua_pushstring(L, type_name);
15+
16+
lua_pushvalue(L, -1);
17+
lua_setfield(L, -3, "__type");
18+
19+
lua_pushcclosure(L, [](lua_State* L) {
20+
lua_pushstring(L, lua_tostring(L, lua_upvalueindex(1)));
21+
return 1;
22+
}, 1);
23+
lua_setfield(L, -2, "__tostring");
24+
}
25+
26+
void assign_to_parent(lua_State* L, lib::element* element) {
27+
lua_getmetatable(L, 2);
28+
lua_getfield(L, -1, "__type");
29+
30+
const char* type = lua_tostring(L, -1);
31+
lua_pop(L, 2);
32+
33+
if (strcmp(type, "Window") == 0) {
34+
auto window = to_class_ptr<lib::window>(L, 2);
35+
window->add_element(element);
36+
}
37+
else if (strcmp(type, "Tab") == 0) {
38+
auto tab = to_class_ptr<lib::tab>(L, 2);
39+
tab->add_element(element);
40+
}
41+
}

0 commit comments

Comments
 (0)