[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: A custom type/class system with lua/luajit
- From: Christian Bielert <cib123@...>
- Date: Fri, 2 Dec 2011 11:42:30 -0800
I'm currently in the process of integrating luajit into my game engine, using its most superb FFI. I have chosen lua for various reasons, among others that I want my own class-system and lua offers the most flexibility in this.
Of course, lua only offers this flexibility by not providing this mechanism in the first place. And sadly, while it does provide the tools to build your own such mechanism, there's no way to adjust its syntax for this. As such, my current plan is to use a preprocessor to create the kind of syntax that I desire, such as "class" constructs or typed function signatures. Unrelated, but the a+=1 syntax wouldn't hurt either :)
In either case, my current concern is mostly the semantics, not the syntax. A thing that I will need pretty early on will be clean, fast type-checks on function entry. http://lua-users.org/wiki/LuaTypeChecking provides some useful information on that, though I personally would prefer something along the lines of:
function param_guard(var, dtype, default)
if not var then return default end
if type(var) ~= dtype then error("Type error") end
end
function foo(a, b, c)
a = param_guard(a, "number")
a = param_guard(b, "string", "nA")
a = param_guard(c, "int")
end
Obviously, the type-checks would have to be extended to also support cdata and custom class-objects, but the point should be clear. It basically reflects a function declaration as it can be found in C++, i.e. in C++ you would write the above code as: void foo(number a, string b = "nA", int c)
My only concern is whether code like this will be efficient, or in fact, if a semantic like this can be achieved at all without huge loss in efficiency. I'm mainly concerned since I know that luajit relies on a lot of internal optimizations, and I'm concerned that a lot of these manual typechecks will make it impossible for some of these optimizations to happen.
Anyway, I'm mainly asking here since I have little experience with lua, and if there are any fundamental flaws with my approach, the sooner I know it the better. :)