Skip to content

Instantly share code, notes, and snippets.

@xanathar
Created June 15, 2016 09:30
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xanathar/2a46845cdcaa1860c4c04ca4e0e28392 to your computer and use it in GitHub Desktop.
Save xanathar/2a46845cdcaa1860c4c04ca4e0e28392 to your computer and use it in GitHub Desktop.
Simple example of Lua integration in C++
//
// main.cpp
// LuaTests
//
// Created by Marco Mastropaolo on 08/06/16.
// Copyright © 2016 Marco Mastropaolo. All rights reserved.
//
#include <iostream>
#include "../include/lua.hpp"
extern "C" int api_getVal(lua_State* lua)
{
lua_pushinteger(lua, 5);
return 1;
}
extern "C" int api_mul(lua_State* lua)
{
lua_settop(lua, 2); // set the size of the stack to 2 and crop useless args
int isnum;
auto num = lua_tointegerx(lua, 1, &isnum);
auto num2 = lua_tointegerx(lua, 2, &isnum);
lua_pushinteger(lua, num * num2);
return 1;
}
void print_error(lua_State* state) {
// The error message is on top of the stack.
// Fetch it, print it and then pop it off the stack.
const char* message = lua_tostring(state, -1);
puts(message);
lua_pop(state, 1);
}
void execute(const char* code)
{
lua_State *state = luaL_newstate();
// Make standard libraries available in the Lua object
luaL_openlibs(state);
lua_register(state, "getVal", api_getVal);
lua_register(state, "mul", api_mul);
int result;
// Load the program; this supports both source code and bytecode files.
result = luaL_loadstring(state, code);
if ( result != LUA_OK ) {
print_error(state);
return;
}
// Finally, execute the program by calling into it.
// Change the arguments if you're not running vanilla Lua code.
result = lua_pcall(state, 0, LUA_MULTRET, 0);
if ( result != LUA_OK ) {
print_error(state);
return;
}
}
int main(int argc, char** argv)
{
execute( R"####(
function fact(n)
if (n == 0) then
return 1
else
return mul(n, fact(n-1))
end
end
print(fact(getVal()))
)####");
return 0;
}
@xanathar
Copy link
Author

Runs the calculation of 5! using C++ calling Lua calling C++.
The factorial is implemented in a Lua script, which calls a getVal() function exposed from C++ which returns 5. It also calls a mul(a,b) function instead of using the multiplication operator to show how to read arguments in C++.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment