Sign in to follow this  

C++ and Lua Lib Thing

Recommended Posts

I was looking at the doc for Boost.Python, and my thoughts returned to my favorite scripting language, Lua, and I thought "What would Boost do?" -- so, to answer that question, I created a prototype library that sits on top of Lua and makes things a bit easier. Here's an example:
float mult(float x, float y) {
	return x * y;
int main(int argc, char **argv) {
	waaagh::vm vm; // create the virtual machine instance
	// run a quick string that declares a function, hello_world
	vm.run_string("hello_world = (function(arg) print('Hello, ' .. arg); end);");
	vm["hello_world"]("world!"); // call the function with a string argument
	// use operator [] to access an lua thing, and then set it to a function pointer
	vm["mult"] = boost::function<float (float, float)>(mult);
	// execute a string that uses our newly "registered" function
	vm.run_string("x = mult(10, 0.5)");
	// access the variable "x" and add 2.5 to it
	float x = (float)vm["x"] + 2.5;
	std::cout << x << std::endl; // outputs 7.5
	vm["x"] = 10.5; // set the variable "x"
	std::cout << (float)vm["x"] << std::endl; // outputs 10.5
	vm.run_string("t = { waaagh = 'good' }");
	std::cout << (std::string)vm["t"]["waaagh"] << std::endl; // outputs 'good'

The waaagh::vm acts a little bit like the _G table in Lua; the code _G["var"] = 5 in Lua is vm["var"] = 5 in C++. There are some limitations to this prototype; you can only call and register functions with 2 or less arguments, and you can't use the return value of an Lua function you call. There's also no error checking; eventually, I'll have to implement some kind of exception based system. What would also be cool is a system to translate std::map and std::vector s into Lua tables; I'd just have to add another template specialization for push_value and get_value. Grab the source here. Just wondering what you think of it; I don't think I've seen C++'s features applied in this way to Lua before.

Share this post

Link to post
Share on other sites
Original post by Rob Loach
That's pretty neat. Can you use something like the Boost library from Lua?

Certain Boost libs, like bind or lambda, wouldn't make sense in Lua. But I'm sure you could expose something like Boost.Filesystem by writing wrappers and registering them.
My thoughts about Boost were more like, "If Boost wrote a library for dealing with Lua, what would it look like?" And then I came up with the idea of using the [] operator on a virtual machine class to access variables.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this