Hacker News new | past | comments | ask | show | jobs | submit login

1. Download lua sources https://www.lua.org/download.html

2. Define your build for the sources (just compile them! No dependencies! Brilliant!) (don't compile lua.c and luac.c if you provide your own main)

3. Integrate with e.g. this main.cpp (if using c++ is your thing, just plain main.c or whatever is binary compatible):

#include <stdio.h>

extern "C" {

#include <lua.h>

#include <lauxlib.h>

#include <lualib.h>

}

// Native function to be called in Lua

static int add_numbers(lua_State* L)

    double a = luaL_checknumber(L, 1);
    double b = luaL_checknumber(L, 2);
    lua_pushnumber(L, a + b);
    return 1;
}

int main() {

    // Instantiate a Lua interpreter
    lua_State L = luaL_newstate();

    // Load Lua libraries
    luaL_openlibs(L);

    // Register native function in Lua
    lua_register(L, "add_numbers", add_numbers);

    // Call native function in Lua
    luaL_dostring(L, "result = add_numbers(10, 20)");
    // Read out the result of the function application
    lua_getglobal(L, "result");
    const char* result = lua_tostring(L, -1);
    printf("The result is: %s\n", result);

    // Define a function in Lua
    luaL_dostring(L, "function concatenate_strings(s1, s2) return s1 .. s2 end");

    // Call Lua function in native side
    luaL_dostring(L, "result = concatenate_strings('Hello, ', 'world!')");

    // Read out the result of the function application
    lua_getglobal(L, "result");
    const char* result2 = lua_tostring(L, -1);
    printf("The result is: %s\n", result2);

    // Close Lua interpreter
    lua_close(L);

    return 0;
}



Yeah this is a perfect example


Happy this helps!




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: