JakobOvrum/LuaD

fix lua_State declaration

belm0 opened this issue · 2 comments

currently:

alias void* lua_State; // TODO: Should be more type-safe

Since Lua API functions accept lua_State*, the result is that D considers them to have void** L in their signature. The following seems to work as a C forward declaration and yields more sensible function types:

struct lua_State;

The following would actually be more useful:

struct lua_State {};

Though not an accurate declaration of the real lua_State, it serves the purpose of opaqueness and type safety given that the API only references it in pointer form.

Why: this allows using L.foo(...) syntax to invoke functions with signature foo(lua_State*, ...). (This syntactic sugar doesn't work with a forward reference.)

I'm interested in this for creating a very thin wrapper around the Lua C API-- essentially one that trims the verbose names (don't need "lua_" prefix on everything when you have namespaces), adds extra type safety (e.g. use bool for boolean rather than int), and adds default args where it makes sense (e.g. pop defaults to 1 element). So someone familiar with the C API can use this immediately while coding succinctly. This could be use for implementing LuaD or other toys. The wrapper functions all get inlined, so there is no overhead.

auto L = newstate(); // i.e. a real C lua_State
scope(exit) L.close();
L.getglobal("foo");
assert(L.isfunction()); // defaults to top of stack, returns actual bool
L.pushstring("bar");
L.call(1);  // defaults to 0 return values

The syntax L.foo(...) not working with opaque struct declaration is considered a compiler bug-- tracking in
http://d.puremagic.com/issues/show_bug.cgi?id=8104.