Skip to content

Instantly share code, notes, and snippets.

@gerred
Forked from jansegre/script.lua
Created December 31, 2016 23:05
Show Gist options
  • Save gerred/262c7973c9e470314cf9a0ce56604978 to your computer and use it in GitHub Desktop.
Save gerred/262c7973c9e470314cf9a0ce56604978 to your computer and use it in GitHub Desktop.
Very basic luajit from Rust.
-- script.lua
-- Receives a table, returns the sum of its components.
io.write("The table the script received has:\n");
x = 0
for i = 1, #foo do
print(i, foo[i])
x = x + foo[i]
end
io.write("Returning data back to C\n");
return x
#![feature(link_args)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
extern crate libc;
use libc::{c_void, c_int, c_double, size_t};
// The reason this is needed is explaines here: http://luajit.org/install.html#embed
#[cfg(target_os="macos", target_arch="x86_64")]
#[link_args = "-pagezero_size 10000 -image_base 100000000"]
extern "system" {}
static LUA_GLOBALSINDEX: i32 = -10002;
static LUA_MULTRET: i32 = -1;
type lua_State = c_void;
type lua_Alloc = extern "C" fn(ud: *mut c_void, ptr: *mut c_void, osize: size_t, nsize: size_t) -> *mut c_void;
type lua_Number = c_double;
// XXX: this is the problematic part, static linking make's luajit break
//#[link(name = "luajit", kind = "static")]
#[link(name = "luajit")]
extern "C" {
fn luaL_newstate() -> *mut lua_State;
fn luaL_openlibs(L: *mut lua_State);
fn lua_pcall(L: *mut lua_State, nargs: c_int, nresults: c_int, errfunc: c_int) -> c_int;
fn lua_settop(L: *mut lua_State, idx: c_int);
fn lua_close(L: *mut lua_State);
fn lua_createtable(L: *mut lua_State, narr: c_int, nrec: c_int);
fn luaL_loadfile(L: *mut lua_State, filename: *const u8) -> c_int;
fn lua_pushnumber(L: *mut lua_State, n: lua_Number);
fn lua_rawset(L: *mut lua_State, idx: c_int);
fn lua_setfield(L: *mut lua_State, idx: c_int, k: *const u8);
fn lua_tonumber(L: *mut lua_State, idx: c_int) -> lua_Number;
}
unsafe fn lua_pop(L: *mut lua_State, n: c_int) { lua_settop(L, -n - 1) }
unsafe fn lua_newtable(L: *mut lua_State) { lua_createtable(L, 0, 0) }
unsafe fn lua_setglobal(L: *mut lua_State, k: *const u8) { lua_setfield(L, LUA_GLOBALSINDEX, k) }
// original example found here: http://lua-users.org/wiki/SimpleLuaApiExample
fn main() {
unsafe {
let L = luaL_newstate();
luaL_openlibs(L);
let status = luaL_loadfile(L, "script.lua".as_ptr());
if status != 0 {
fail!("Couldn't load file.");
}
lua_newtable(L);
for i in range(1i, 6) {
lua_pushnumber(L, i as f64);
lua_pushnumber(L, (i * 2) as f64);
lua_rawset(L, -3);
}
lua_setglobal(L, "foo".as_ptr());
let result = lua_pcall(L, 0, LUA_MULTRET, 0);
if result != 0 {
fail!("Failed to run script.");
}
let sum = lua_tonumber(L, -1);
println!("Script returned: {:0.f}", sum);
lua_pop(L, 1);
lua_close(L);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment