Skip to content

Instantly share code, notes, and snippets.

@karlbunch
Forked from benbjohnson/lj.go
Last active August 29, 2015 14:12
Show Gist options
  • Save karlbunch/369a245d8b79fbf41121 to your computer and use it in GitHub Desktop.
Save karlbunch/369a245d8b79fbf41121 to your computer and use it in GitHub Desktop.
package main
/*
#cgo CFLAGS: -I/usr/local/include
#cgo LDFLAGS: -L/usr/local/lib -lluajit-5.1
#include <stdlib.h>
#include <stdio.h>
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lualib.h>
#include <luajit-2.0/lauxlib.h>
int a_c_func(const char arg[]) {
printf("a_c_func(%s) called\n", arg);
return 0;
}
*/
import "C"
import (
"fmt"
"os"
"unsafe"
)
const src = `
local ffi = require('ffi')
ffi.cdef([[
int a_c_func(const char arg[]);
]])
print("Hello from Lua!")
ffi.C.a_c_func("LUA")
print("Goodbye from Lua!")
`
func main() {
C.a_c_func(C.CString("MAIN"))
// Initialize state.
state := C.luaL_newstate()
if state == nil {
fmt.Println("Unable to initialize Lua context.")
os.Exit(1)
}
C.luaL_openlibs(state)
// Compile the script.
csrc := C.CString(src)
defer C.free(unsafe.Pointer(csrc))
if C.luaL_loadstring(state, csrc) != 0 {
errstring := C.GoString(C.lua_tolstring(state, -1, nil))
fmt.Printf("Lua error: %v\n", errstring)
os.Exit(1)
}
// Run script.
if C.lua_pcall(state, 0, 0, 0) != 0 {
errstring := C.GoString(C.lua_tolstring(state, -1, nil))
fmt.Printf("Lua execution error: %v\n", errstring)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment