Lua.cpp: Get rid of register-queue
[lsnes.git] / include / library / lua-base.hpp
blob7f309bed5802e34fb98898ea5c6eee23877dc848
1 #ifndef _library__lua_base__hpp__included__
2 #define _library__lua_base__hpp__included__
4 #include <string>
5 #include <stdexcept>
6 #include <typeinfo>
7 #include <typeindex>
8 #include <map>
9 #include <unordered_map>
10 #include <set>
11 #include <list>
12 #include <cassert>
13 #include "string.hpp"
14 #include "utf8.hpp"
15 extern "C"
17 #include <lua.h>
20 namespace lua
22 class state;
23 class function;
24 class function_group;
25 class class_group;
26 class class_base;
28 /**
29 * Lua state object.
31 class state
33 public:
34 //Auxillary type for store-tag.
35 template<typename T> struct _store_tag
37 T& addr;
38 T val;
39 _store_tag(T& a, T v) : addr(a), val(v) {}
41 //Auxillary type for vararg-tag.
42 struct vararg_tag
44 std::list<std::string> args;
45 vararg_tag(std::list<std::string>& _args) : args(_args) {}
46 int pushargs(state& L);
49 //Auxillary type for numeric-tag.
50 template<typename T> struct _numeric_tag
52 T val;
53 _numeric_tag(T v) : val(v) {}
56 //Auxillary type for fnptr-tag.
57 template<typename T> struct _fnptr_tag
59 int(*fn)(state& L, T v);
60 T val;
61 _fnptr_tag(int (*f)(state& L, T v), T v) : fn(f), val(v) {}
64 //Auxillary type for fn-tag.
65 template<typename T> struct _fn_tag
67 T fn;
68 _fn_tag(T f) : fn(f) {}
71 /**
72 * Callback parameter: Don't pass any real parameter, but instead store specified value in specified
73 * location.
75 * Parameter a: The location to store value to.
76 * Parameter v: The value to store.
77 * Returns: The parameter structure.
79 template<typename T> static struct _store_tag<T> store_tag(T& a, T v) { return _store_tag<T>(a, v); }
80 /**
81 * Callback parameter: Pass numeric value.
83 * Parameter v: The value to pass.
84 * Returns: The parameter structure.
86 template<typename T> static struct _numeric_tag<T> numeric_tag(T v) { return _numeric_tag<T>(v); }
88 /**
89 * Callback parameter: Execute function to push more parameters.
91 * Parameter f: The function to execute. The return value is number of additional parameters pushed.
92 * Parameter v: The value to pass to function.
93 * Returns: The parameter structure.
95 template<typename T> static struct _fnptr_tag<T> fnptr_tag(int (*f)(state& L, T v), T v)
97 return _fnptr_tag<T>(f, v);
101 * Callback parameter: Execute function to push more parameters.
103 * Parameter v: The functor to execute. Passed reference to the Lua state. The return value is number of
104 * additional parameters pushed.
105 * Returns: The parameter structure.
107 template<typename T> static struct _fn_tag<T> fn_tag(T v) { return _fn_tag<T>(v); }
110 * Callback parameter: Pass boolean argument.
112 * Parameter v: The boolean value to pass.
114 struct boolean_tag { bool val; boolean_tag(bool v) : val(v) {}};
117 * Callback parameter: Pass string argument.
119 * Parameter v: The string value to pass.
121 struct string_tag { std::string val; string_tag(const std::string& v) : val(v) {}};
124 * Callback parameter: Pass nil argument.
126 struct nil_tag { nil_tag() {}};
127 private:
128 template<typename U, typename... T> void _callback(int argc, _store_tag<U> tag, T... args)
130 tag.addr = tag.val;
131 _callback(argc, args...);
132 tag.addr = NULL;
135 template<typename... T> void _callback(int argc, vararg_tag tag, T... args)
137 int e = tag.pushargs(*this);
138 _callback(argc + e, args...);
141 template<typename... T> void _callback(int argc, nil_tag tag, T... args)
143 pushnil();
144 _callback(argc + 1, args...);
147 template<typename... T> void _callback(int argc, boolean_tag tag, T... args)
149 pushboolean(tag.val);
150 _callback(argc + 1, args...);
153 template<typename... T> void _callback(int argc, string_tag tag, T... args)
155 pushlstring(tag.val.c_str(), tag.val.length());
156 _callback(argc + 1, args...);
159 template<typename U, typename... T> void _callback(int argc, _numeric_tag<U> tag, T... args)
161 pushnumber(tag.val);
162 _callback(argc + 1, args...);
165 template<typename U, typename... T> void _callback(int argc, _fnptr_tag<U> tag, T... args)
167 int extra = tag.fn(*this, tag.val);
168 _callback(argc + extra, args...);
171 template<typename U, typename... T> void _callback(int argc, _fn_tag<U> tag, T... args)
173 int extra = tag.fn(*this);
174 _callback(argc + extra, args...);
177 void _callback(int argc)
179 int r = pcall(argc, 0, 0);
180 if(r == LUA_ERRRUN) {
181 (stringfmt() << "Error running Lua callback: " << tostring(-1)).throwex();
182 pop(1);
184 if(r == LUA_ERRMEM) {
185 (stringfmt() << "Error running Lua callback: Out of memory").throwex();
186 pop(1);
188 if(r == LUA_ERRERR) {
189 (stringfmt() << "Error running Lua callback: Double Fault???").throwex();
190 pop(1);
193 public:
195 * Create a new state.
197 state() throw(std::bad_alloc);
199 * Create a new state with specified master state.
201 state(state& _master, lua_State* L);
203 * Destroy a state.
205 ~state() throw();
207 * Get the internal state object.
209 * Return value: Internal state.
211 lua_State* handle() { return lua_handle; }
213 * Get the master state.
215 state& get_master() { return master ? master->get_master() : *this; }
217 * Set the internal state object.
219 void handle(lua_State* l) { lua_handle = l; }
221 * Set OOM handler.
223 void set_oom_handler(void (*oom)()) { oom_handler = oom ? oom : builtin_oom; }
225 * Reset the state.
227 void reset() throw(std::runtime_error, std::bad_alloc);
229 * Deinit the state.
231 void deinit() throw();
233 * Get a string argument.
235 * Parameter argindex: The stack index.
236 * Parameter fname: The name of function to use in error messages.
237 * Returns: The string.
238 * Throws std::runtime_error: The specified argument is not a string.
240 std::string get_string(int argindex, const std::string& fname) throw(std::runtime_error, std::bad_alloc)
242 if(lua_isnone(lua_handle, argindex))
243 (stringfmt() << "argument #" << argindex << " to " << fname << " must be string").throwex();
244 size_t len;
245 const char* f = lua_tolstring(lua_handle, argindex, &len);
246 if(!f)
247 (stringfmt() << "argument #" << argindex << " to " << fname << " must be string").throwex();
248 return std::string(f, f + len);
251 * Get a boolean argument.
253 * Parameter argindex: The stack index.
254 * Parameter fname: The name of function to use in error messages.
255 * Returns: The string.
256 * Throws std::runtime_error: The specified argument is not a boolean.
258 bool get_bool(int argindex, const std::string& fname) throw(std::runtime_error, std::bad_alloc)
260 if(lua_isnone(lua_handle, argindex) || !lua_isboolean(lua_handle, argindex))
261 (stringfmt() << "argument #" << argindex << " to " << fname << " must be boolean").throwex();
262 return (lua_toboolean(lua_handle, argindex) != 0);
265 * Get a mandatory numeric argument.
267 * Parameter argindex: The stack index.
268 * Parameter fname: The name of function to use in error messages.
269 * Returns: The parsed number.
270 * Throws std::runtime_error: Bad type.
272 template<typename T>
273 T get_numeric_argument(int argindex, const std::string& fname)
275 if(lua_isnone(lua_handle, argindex) || !lua_isnumber(lua_handle, argindex))
276 (stringfmt() << "Argument #" << argindex << " to " << fname << " must be numeric").throwex();
277 return static_cast<T>(lua_tonumber(lua_handle, argindex));
280 * Get a optional numeric argument.
282 * Parameter argindex: The stack index.
283 * Parameter value: The place to store the value.
284 * Parameter fname: The name of function to use in error messages.
285 * Throws std::runtime_error: Bad type.
287 template<typename T>
288 void get_numeric_argument(unsigned argindex, T& value, const std::string& fname)
290 if(lua_isnoneornil(lua_handle, argindex))
291 return;
292 if(lua_isnone(lua_handle, argindex) || !lua_isnumber(lua_handle, argindex))
293 (stringfmt() << "Argument #" << argindex << " to " << fname << " must be numeric if "
294 "present").throwex();
295 value = static_cast<T>(lua_tonumber(lua_handle, argindex));
298 * Do a callback.
300 * Parameter name: The name of the callback.
301 * Parameter args: Arguments to pass to the callback.
303 template<typename... T>
304 bool callback(const std::string& name, T... args)
306 getglobal(name.c_str());
307 int t = type(-1);
308 if(t != LUA_TFUNCTION) {
309 pop(1);
310 return false;
312 _callback(0, args...);
313 return true;
316 * Do a callback.
318 * Parameter cblist: List of environment keys to do callbacks.
319 * Parameter args: Arguments to pass to the callback.
321 template<typename... T>
322 bool callback(const std::list<char>& cblist, T... args)
324 bool any = false;
325 for(auto& i : cblist) {
326 pushlightuserdata(const_cast<char*>(&i));
327 rawget(LUA_REGISTRYINDEX);
328 int t = type(-1);
329 if(t != LUA_TFUNCTION) {
330 pop(1);
331 } else {
332 _callback(0, args...);
333 any = true;
336 return any;
339 * Add a group of functions.
341 void add_function_group(function_group& group);
343 * Add a group of classes.
345 void add_class_group(class_group& group);
347 * Function callback.
349 void function_callback(const std::string& name, function* func);
351 * Class callback.
353 void class_callback(const std::string& name, class_base* func);
355 * Do something just once per VM.
357 * Parameter key: The do-once key value.
358 * Returns: True if called the first time for given key on given VM, false otherwise.
360 bool do_once(void* key);
362 * Callback list.
364 class callback_list
366 public:
367 callback_list(state& L, const std::string& name, const std::string& fn_cbname = "");
368 ~callback_list();
369 void _register(state& L); //Reads callback from top of lua stack.
370 void _unregister(state& L); //Reads callback from top of lua stack.
371 template<typename... T> bool callback(T... args) {
372 bool any = L.callback(callbacks, args...);
373 if(fn_cbname != "" && L.callback(fn_cbname, args...))
374 any = true;
375 return any;
377 const std::string& get_name() { return name; }
378 void clear() { callbacks.clear(); }
379 private:
380 callback_list(const callback_list&);
381 callback_list& operator=(const callback_list&);
382 std::list<char> callbacks;
383 state& L;
384 std::string name;
385 std::string fn_cbname;
388 * Enumerate all callbacks.
390 std::list<callback_list*> get_callbacks();
392 * Register/Unregister a callback list.
394 void do_register(const std::string& name, callback_list& callback);
395 void do_unregister(const std::string& name, callback_list& callback);
397 //All kinds of Lua API functions.
398 void pop(int n) { lua_pop(lua_handle, n); }
399 void* newuserdata(size_t size) { return lua_newuserdata(lua_handle, size); }
400 int setmetatable(int index) { return lua_setmetatable(lua_handle, index); }
401 int type(int index) { return lua_type(lua_handle, index); }
402 int getmetatable(int index) { return lua_getmetatable(lua_handle, index); }
403 int rawequal(int index1, int index2) { return lua_rawequal(lua_handle, index1, index2); }
404 void* touserdata(int index) { return lua_touserdata(lua_handle, index); }
405 const void* topointer(int index) { return lua_topointer(lua_handle, index); }
406 int gettop() { return lua_gettop(lua_handle); }
407 void pushvalue(int index) { lua_pushvalue(lua_handle, index); }
408 void pushlightuserdata(void* p) { lua_pushlightuserdata(lua_handle, p); }
409 void rawset(int index) { lua_rawset(lua_handle, index); }
410 void pushnil() { lua_pushnil(lua_handle); }
411 void pushstring(const char* s) { lua_pushstring(lua_handle, s); }
412 void rawget(int index) { lua_rawget(lua_handle, index); }
413 int isnil(int index) { return lua_isnil(lua_handle, index); }
414 void newtable() { lua_newtable(lua_handle); }
415 void pushcclosure(lua_CFunction fn, int n) { lua_pushcclosure(lua_handle, fn, n); }
416 void pushcfunction(lua_CFunction fn) { lua_pushcfunction(lua_handle, fn); }
417 void setfield(int index, const char* k) { lua_setfield(lua_handle, index, k); }
418 void getfield(int index, const char* k) { lua_getfield(lua_handle, index, k); }
419 void getglobal(const char* name) { lua_getglobal(lua_handle, name); }
420 void setglobal(const char* name) { lua_setglobal(lua_handle, name); }
421 void insert(int index) { lua_insert(lua_handle, index); }
422 void settable(int index) { lua_settable(lua_handle, index); }
423 int isnone(int index) { return lua_isnone(lua_handle, index); }
424 void pushnumber(lua_Number n) { return lua_pushnumber(lua_handle, n); }
425 int isnumber(int index) { return lua_isnumber(lua_handle, index); }
426 int isboolean(int index) { return lua_isboolean(lua_handle, index); }
427 int toboolean(int index) { return lua_toboolean(lua_handle, index); }
428 const char* tolstring(int index, size_t *len) { return lua_tolstring(lua_handle, index, len); }
429 void pushboolean(int b) { lua_pushboolean(lua_handle, b); }
430 lua_Number tonumber(int index) { return lua_tonumber(lua_handle, index); }
431 void gettable(int index) { lua_gettable(lua_handle, index); }
432 #if LUA_VERSION_NUM == 501
433 int load(lua_Reader reader, void* data, const char* chunkname) { return lua_load(lua_handle, reader, data,
434 chunkname); }
435 #endif
436 #if LUA_VERSION_NUM == 502
437 int load(lua_Reader reader, void* data, const char* chunkname, const char* mode) { return lua_load(lua_handle,
438 reader, data, chunkname, mode); }
439 #endif
440 const char* tostring(int index) { return lua_tostring(lua_handle, index); }
441 const char* tolstring(int index, size_t& len) { return lua_tolstring(lua_handle, index, &len); }
442 void pushlstring(const char* s, size_t len) { lua_pushlstring(lua_handle, s, len); }
443 void pushlstring(const std::string& s) { lua_pushlstring(lua_handle, s.c_str(), s.length()); }
444 void pushlstring(const char32_t* s, size_t len) { pushlstring(utf8::to8(std::u32string(s, len))); }
445 int pcall(int nargs, int nresults, int errfunc) { return lua_pcall(lua_handle, nargs, nresults, errfunc); }
446 int next(int index) { return lua_next(lua_handle, index); }
447 int isnoneornil(int index) { return lua_isnoneornil(lua_handle, index); }
448 lua_Integer tointeger(int index) { return lua_tointeger(lua_handle, index); }
449 void rawgeti(int index, int n) { lua_rawgeti(lua_handle, index, n); }
450 private:
451 static void builtin_oom();
452 static void* builtin_alloc(void* user, void* old, size_t olds, size_t news);
453 void (*oom_handler)();
454 state* master;
455 lua_State* lua_handle;
456 state(state&);
457 state& operator=(state&);
462 #endif