Debian Codegraph @

CorsixTH/Src/th_lua.h

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #ifndef CORSIX_TH_TH_LUA_H_
24 #define CORSIX_TH_TH_LUA_H_
25 #include "config.h"
26
27 #include <cassert>
28 #include <cstdio>
29 #include <cstring>
30 #include <initializer_list>
31 #include <memory>
32 #include <new>
33 #include <type_traits>
34
35 #include "lua.hpp"
36
37 class lua_state_deleter {
38 public:
39 void operator()(lua_State* L) const { lua_close(L); }
40 };
41
42 //! \brief Unique pointer for lua_State
43 using lua_state_unique_ptr = std::unique_ptr<lua_State, lua_state_deleter>;
44
45 int luaopen_th(lua_State* L);
46
47 // Print debugging helper functions
48
49 void luaT_printvalue(lua_State* L, int idx);
50
51 void luaT_printstack(lua_State* L);
52
53 void luaT_printrawtable(lua_State* L, int idx);
54
55 //! Lua 5.3 lua_rotate backported to 5.1+
56 /*!
57 /sa https://www.lua.org/manual/5.4/manual.html#lua_rotate
58 */
59 inline void luaT_rotate(lua_State* L, int idx, int n) {
60 #if LUA_VERSION_NUM >= 503
61 lua_rotate(L, idx, n);
62 #else
63 if (n < 0) {
64 if (idx < 0) {
65 idx = lua_gettop(L) + idx + 1;
66 }
67 n = lua_gettop(L) - idx + 1 + n;
68 }
69
70 for (int i = 0; i < n; i++) {
71 lua_insert(L, idx);
72 }
73 #endif
74 }
75
76 // Compatibility layer for removal of environments in 5.2
77 #if LUA_VERSION_NUM >= 502
78 const int luaT_environindex = lua_upvalueindex(1);
79 #else
80 const int luaT_environindex = LUA_ENVIRONINDEX;
81 #endif
82
83 inline int luaT_upvalueindex(int i) {
84 #if LUA_VERSION_NUM >= 502
85 return lua_upvalueindex(i + 1);
86 #else
87 return lua_upvalueindex(i);
88 #endif
89 }
90
91 //! Compatibility function for Lua 5.1 luaL_register
92 /*!
93 luaL_register was removed in Lua 5.2.
94
95 \param L The lua state
96 \param n The name of the library to register
97 \param l An array of functions to register in the library
98 \sa https://www.lua.org/manual/5.1/manual.html#luaL_register
99 */
100 template <class Collection>
101 inline void luaT_register(lua_State* L, const char* n, Collection& l) {
102 #if LUA_VERSION_NUM >= 502
103 lua_createtable(L, 0, static_cast<int>(l.size()));
104 lua_pushvalue(L, luaT_environindex);
105 luaL_setfuncs(L, l.data(), 1);
106 lua_pushvalue(L, -1);
107 lua_setglobal(L, n);
108 #else
109 luaL_register(L, n, l.data());
110 #endif
111 }
112
113 //! Register functions into the table on top of the stack
114 /*!
115 \param L The lua state
116 \param R An array of functions to register
117 \sa https://www.lua.org/manual/5.1/manual.html#luaL_register
118 */
119 inline void luaT_setfuncs(lua_State* L, const luaL_Reg* R) {
120 #if LUA_VERSION_NUM >= 502
121 lua_pushvalue(L, luaT_environindex);
122 luaL_setfuncs(L, R, 1);
123 #else
124 luaL_register(L, nullptr, R);
125 #endif
126 }
127
128 inline void luaT_pushcclosure(lua_State* L, lua_CFunction f, int nups) {
129 #if LUA_VERSION_NUM >= 502
130 ++nups;
131 lua_pushvalue(L, luaT_environindex);
132 lua_insert(L, -nups);
133 lua_pushcclosure(L, f, nups);
134 #else
135 lua_pushcclosure(L, f, nups);
136 #endif
137 }
138
139 inline void luaT_pushcfunction(lua_State* L, lua_CFunction f) {
140 luaT_pushcclosure(L, f, 0);
141 }
142
143 inline int luaT_cpcall(lua_State* L, lua_CFunction f, void* u) {
144 #if LUA_VERSION_NUM >= 502
145 lua_checkstack(L, 2);
146 lua_pushcfunction(L, f);
147 lua_pushlightuserdata(L, u);
148 return lua_pcall(L, 1, 0, 0);
149 #else
150 return lua_cpcall(L, f, u);
151 #endif
152 }
153
154 // Compatibility for missing mode argument on lua_load in 5.1
155 inline int luaT_load(lua_State* L, lua_Reader r, void* d, const char* s,
156 const char* m) {
157 #if LUA_VERSION_NUM >= 502
158 return lua_load(L, r, d, s, m);
159 #else
160 return lua_load(L, r, d, s);
161 #endif
162 }
163
164 // Compatibility for older versions of lua_resume
165 inline int luaT_resume(lua_State* L, lua_State* f, int n, int* nresults) {
166 #if LUA_VERSION_NUM >= 504
167 return lua_resume(L, f, n, nresults);
168 #elif LUA_VERSION_NUM >= 502
169 int res = lua_resume(L, f, n);
170 *nresults = lua_gettop(L);
171 return res;
172 #else
173 int res = lua_resume(L, n);
174 *nresults = lua_gettop(L);
175 return res;
176 #endif
177 }
178
179 //! Version of operator new which allocates into a Lua userdata
180 /*!
181 If a specific constructor of T is required, then call like:
182 T* variable = luaT_new<T>(L, constructor arguments);
183 If the default constructor is wanted, it can be called like:
184 T* variable = luaT_new<T>(L);
185 See also luaT_stdnew() which allocates, and also sets up the environment
186 table and metatable for the userdata.
187 */
188 template <typename T, typename... Ts>
189 T* luaT_new(lua_State* L, Ts... args) {
190 return new (lua_newuserdata(L, sizeof(T))) T(args...);
191 }
192
193 //! Check that a Lua argument is a binary data blob
194 /*!
195 If the given argument is a string or (full) userdata, then returns a
196 pointer to the start of it, and the length of it. Otherwise, throws a
197 Lua error.
198 */
199 const uint8_t* luaT_checkfile(lua_State* L, int idx, size_t* pDataLen);
200
201 //! Check that a Lua argument is a string or a proxied string
202 const char* luaT_checkstring(lua_State* L, int idx, size_t* pLength);
203
204 //! Push a C closure as a callable table
205 void luaT_pushcclosuretable(lua_State* L, lua_CFunction fn, int n);
206
207 //! Set a field on the environment table of a value
208 /*!
209 Performs: env(stack[index])[k] = top; pop()
210 */
211 void luaT_setenvfield(lua_State* L, int index, const char* k);
212
213 //! Get a field from the environment table of a value
214 /*!
215 Performs: push(env(stack[index])[k])
216 */
217 void luaT_getenvfield(lua_State* L, int index, const char* k);
218
219 template <class T, typename... Args>
220 inline T* luaT_stdnew(lua_State* L, int mt_idx = luaT_environindex,
221 bool env = false, Args&&... args) {
222 T* p = luaT_new<T>(L, std::forward<Args>(args)...);
223 lua_pushvalue(L, mt_idx);
224 lua_setmetatable(L, -2);
225 if (env) {
226 lua_newtable(L);
227 lua_setfenv(L, -2);
228 }
229 return p;
230 }
231
232 template <typename T>
233 struct luaT_classinfo {};
234
235 class render_target;
236 template <>
237 struct luaT_classinfo<render_target> {
238 static inline const char* name() { return "Surface"; }
239 };
240
241 class level_map;
242 template <>
243 struct luaT_classinfo<level_map> {
244 static inline const char* name() { return "Map"; }
245 };
246
247 class sprite_sheet;
248 template <>
249 struct luaT_classinfo<sprite_sheet> {
250 static inline const char* name() { return "SpriteSheet"; }
251 };
252
253 class animation;
254 template <>
255 struct luaT_classinfo<animation> {
256 static inline const char* name() { return "Animation"; }
257 };
258
259 class animation_manager;
260 template <>
261 struct luaT_classinfo<animation_manager> {
262 static inline const char* name() { return "Animator"; }
263 };
264
265 class palette;
266 template <>
267 struct luaT_classinfo<palette> {
268 static inline const char* name() { return "Palette"; }
269 };
270
271 class raw_bitmap;
272 template <>
273 struct luaT_classinfo<raw_bitmap> {
274 static inline const char* name() { return "RawBitmap"; }
275 };
276
277 class font;
278 template <>
279 struct luaT_classinfo<font> {
280 static inline const char* name() { return "Font"; }
281 };
282
283 class bitmap_font;
284 template <>
285 struct luaT_classinfo<bitmap_font> {
286 static inline const char* name() { return "BitmapFont"; }
287 };
288
289 class freetype_font;
290 template <>
291 struct luaT_classinfo<freetype_font> {
292 static inline const char* name() { return "FreeTypeFont"; }
293 };
294
295 struct layers;
296 template <>
297 struct luaT_classinfo<layers> {
298 static inline const char* name() { return "Layers"; }
299 };
300
301 class pathfinder;
302 template <>
303 struct luaT_classinfo<pathfinder> {
304 static inline const char* name() { return "Pathfinder"; }
305 };
306
307 class cursor;
308 template <>
309 struct luaT_classinfo<cursor> {
310 static inline const char* name() { return "Cursor"; }
311 };
312
313 class line_sequence;
314 template <>
315 struct luaT_classinfo<line_sequence> {
316 static inline const char* name() { return "Line"; }
317 };
318
319 class music;
320 template <>
321 struct luaT_classinfo<music> {
322 static inline const char* name() { return "Music"; }
323 };
324
325 class sound_archive;
326 template <>
327 struct luaT_classinfo<sound_archive> {
328 static inline const char* name() { return "SoundArchive"; }
329 };
330
331 class sound_player;
332 template <>
333 struct luaT_classinfo<sound_player> {
334 static inline const char* name() { return "SoundEffects"; }
335 };
336
337 class movie_player;
338 template <>
339 struct luaT_classinfo<movie_player> {
340 static inline const char* name() { return "Movie"; }
341 };
342
343 class abstract_window;
344 template <>
345 struct luaT_classinfo<abstract_window> {
346 static inline const char* name() { return "WindowBase"; }
347 };
348
349 class sprite_render_list;
350 template <>
351 struct luaT_classinfo<sprite_render_list> {
352 static inline const char* name() { return "SpriteRenderList"; }
353 };
354
355 class string_proxy;
356 template <>
357 struct luaT_classinfo<string_proxy> {
358 static inline const char* name() { return "StringProxy"; }
359 };
360
361 class lfs_ext;
362 template <>
363 struct luaT_classinfo<lfs_ext> {
364 static inline const char* name() { return "LfsExt"; }
365 };
366
367 class iso_filesystem;
368 template <>
369 struct luaT_classinfo<iso_filesystem> {
370 static inline const char* name() { return "ISO Filesystem"; }
371 };
372
373 class th_lua_midi_player;
374 template <>
375 struct luaT_classinfo<th_lua_midi_player> {
376 static inline const char* name() { return "MidiPlayer"; }
377 };
378
379 template <class T>
380 T* luaT_testuserdata(lua_State* L, int idx, int mt_idx, bool required = true) {
381 // Turn mt_idx into an absolute index, as the stack size changes.
382 if (mt_idx > LUA_REGISTRYINDEX && mt_idx < 0) {
383 mt_idx = lua_gettop(L) + mt_idx + 1;
384 }
385
386 void* ud = lua_touserdata(L, idx);
387 if (ud != nullptr && lua_getmetatable(L, idx) != 0) {
388 while (true) {
389 if (lua_equal(L, mt_idx, -1) != 0) {
390 lua_pop(L, 1);
391 return static_cast<T*>(ud);
392 }
393 // Go up one inheritance level, if there is one.
394 if (lua_type(L, -1) != LUA_TTABLE) break;
395 lua_rawgeti(L, -1, 1);
396 lua_replace(L, -2);
397 }
398 lua_pop(L, 1);
399 }
400
401 if (required) {
402 const char* msg =
403 lua_pushfstring(L, "%s expected, got %s", luaT_classinfo<T>::name(),
404 luaL_typename(L, idx));
405 luaL_argerror(L, idx, msg);
406 assert(false); // unreachable
407 }
408 return nullptr;
409 }
410
411 template <class T>
412 T* luaT_testuserdata(lua_State* L, int idx = 1, bool required = true) {
413 int iMetaIndex = luaT_environindex;
414 if (idx > 1) iMetaIndex = luaT_upvalueindex(idx - 1);
415 return luaT_testuserdata<T>(L, idx, iMetaIndex, required);
416 }
417
418 template <class T, int mt>
419 int luaT_stdgc(lua_State* L) {
420 T* p = luaT_testuserdata<T>(L, 1, mt, false);
421 if (p != nullptr) {
422 p->~T();
423 }
424 return 0;
425 }
426
427 void luaT_execute(lua_State* L, const char* sLuaString);
428 void luaT_execute_loadstring(lua_State* L, const char* sLuaString);
429
430 void luaT_push(lua_State* L, lua_CFunction f);
431 void luaT_push(lua_State* L, int i);
432 void luaT_push(lua_State* L, const char* s);
433
434 template <class T>
435 void luaT_execute(lua_State* L, const char* sLuaString, T arg) {
436 luaT_execute_loadstring(L, sLuaString);
437 luaT_push(L, arg);
438 lua_call(L, 1, LUA_MULTRET);
439 }
440
441 template <class T1, class T2>
442 void luaT_execute(lua_State* L, const char* sLuaString, T1 arg1, T2 arg2) {
443 luaT_execute_loadstring(L, sLuaString);
444 luaT_push(L, arg1);
445 luaT_push(L, arg2);
446 lua_call(L, 2, LUA_MULTRET);
447 }
448
449 template <class T1, class T2, class T3>
450 void luaT_execute(lua_State* L, const char* sLuaString, T1 arg1, T2 arg2,
451 T3 arg3) {
452 luaT_execute_loadstring(L, sLuaString);
453 luaT_push(L, arg1);
454 luaT_push(L, arg2);
455 luaT_push(L, arg3);
456 lua_call(L, 3, LUA_MULTRET);
457 }
458
459 template <class T1, class T2, class T3, class T4>
460 void luaT_execute(lua_State* L, const char* sLuaString, T1 arg1, T2 arg2,
461 T3 arg3, T4 arg4) {
462 luaT_execute_loadstring(L, sLuaString);
463 luaT_push(L, arg1);
464 luaT_push(L, arg2);
465 luaT_push(L, arg3);
466 luaT_push(L, arg4);
467 lua_call(L, 4, LUA_MULTRET);
468 }
469
470 void luaT_pushtablebool(lua_State* L, const char* k, bool v);
471
472 void preload_lua_package(lua_State* L, const char* name, lua_CFunction fn);
473
474 namespace {
475 int luaT_get_userdata_classname(lua_State* L, int idx, const char** class_name,
476 void** userdata) {
477 void* p = lua_touserdata(L, idx);
478 *userdata = p;
479 if (p == nullptr) {
480 return 0;
481 }
482 int added_stack = 0;
483 if (lua_getmetatable(L, idx) == 0) {
484 std::printf("Warn: No metatable for userdata\n");
485 return 0;
486 }
487 lua_getfield(L, -1, "__index");
488 added_stack += 2; // metadata and field
489 if (lua_type(L, -1) != LUA_TTABLE) {
490 lua_pop(L, added_stack);
491 std::printf("Warn: No __index field method table for userdata\n");
492 return 0;
493 }
494
495 if (lua_getmetatable(L, -1) == 0) {
496 lua_pop(L, added_stack);
497 std::printf("Warn: No metatable for method table of userdata\n");
498 return 0;
499 }
500 lua_getfield(L, -1, "__class_name");
501 added_stack += 2; // method metatable and class name field
502 if (lua_type(L, -1) != LUA_TSTRING) {
503 lua_pop(L, added_stack);
504 std::printf("Warn: No __class_name field for userdata\n");
505 return 0;
506 }
507 *class_name = lua_tostring(L, -1);
508
509 return added_stack;
510 }
511 } // namespace
512
513 // Find the appropriate derived class of base for a given
514 // userdata object.
515 //
516 // th_lua_internal.h defines our c++ binding class metatables:
517 // metatable: { __index = method_table, ... }
518 // method_table: { ... }
519 // method_table metatable: { __class_name = class_name }
520 template <typename B, typename T1, typename T2>
521 B* luaT_touserdata_base(lua_State* L, int idx,
522 const std::initializer_list<const char*>& class_names) {
523 static_assert(std::is_base_of<B, T1>::value, "B must be a base class for T1");
524 static_assert(std::is_base_of<B, T2>::value, "B must be a base class for T2");
525
526 const char* class_name = nullptr;
527 void* p;
528
529 int stack = luaT_get_userdata_classname(L, idx, &class_name, &p);
530 if (class_name == nullptr) {
531 return nullptr;
532 }
533
534 auto it = class_names.begin();
535 if (std::strcmp(class_name, *it) == 0) {
536 lua_pop(L, stack);
537 return static_cast<T1*>(p);
538 }
539 it++;
540 if (std::strcmp(class_name, *it) == 0) {
541 lua_pop(L, stack);
542 return static_cast<T2*>(p);
543 }
544 std::printf("Warn: Unknown class name for usertype %s\n", class_name);
545 lua_pop(L, stack);
546 return nullptr;
547 }
548
549 #endif // CORSIX_TH_TH_LUA_H_