Writing C++ bindings for Lua is a little more complicated than writing regular C bindings generally. There are things like LuaBind which can automate the process which some people find useful. If you just want to learn how to do simple Lua to C bindings by hand, you should read this (and keep this page handy too). Even if you're not going to do it by hand and decide to go with an automated approach, you should read it anyway so you can understand what's going on under the hood.
Writing bindings for C++ is harder for a few reasons. Lua only uses void*
s to store your C/C++ objects, so you lose a lot of your type safety. There are also idioms in C++ like RAII that don't translate to Lua as well.
However, if you want to write your own lua bindings for C++ like I did, you can use LuaWrapper. I wrote it for my own game but I put it online in case others find it useful. It handles some of the issues I was running into when using C++ and Lua together, like ensuring that C++ objects are garbage collected properly and making sure when you pass them back and forth between C++ and Lua you always have the right type. You'll need to understand how Lua and regular C fit together to use it though. You can look at this example project I put up that shows how to use LuaWrapper to bind to C++ objects in Lua.
Since you mention getters and setters, I'll also mention I just recently added a second file to LuaWrapper that contains a bunch of common patterns I was using in my code (this isn't in the example project yet). For example, I have a C++ object called a Style which represents how a UI widget will look in various states. To write the getters and setters for that objcet in C++ all I needed to do was add this to create getters and setters in Lua:
static luaL_reg Style_Metatable[] =
{
// Type Member type Field
{ "idle", luaU_getset<Style, TextureGroup, &Style::Idle> },
{ "hover", luaU_getset<Style, TextureGroup, &Style::Hover> },
{ "pressed", luaU_getset<Style, TextureGroup, &Style::Pressed> },
{ "focusedIdle", luaU_getset<Style, TextureGroup, &Style::FocusedIdle> },
{ "focusedHover", luaU_getset<Style, TextureGroup, &Style::FocusedHover> },
{ "focusedPressed", luaU_getset<Style, TextureGroup, &Style::FocusedPressed> },
{ "disabled", luaU_getset<Style, TextureGroup, &Style::Disabled> },
{ NULL, NULL }
};
int luaopen_Style(lua_State* L)
{
luaW_register<Style>(L, "Style", NULL, Style_Metatable);
return 1;
}
That allows me to do this in Lua:
buttonStyle = Style.new()
Style:idle(buttonIdleBorder)
Style:hover(buttonHoverBorder)
Style:pressed(buttonPressedBorder)