Git Product home page Git Product logo

golua's Introduction

Go Bindings for the lua C API

Build Status

Simplest way to install:

# go get github.com/aarzilli/golua/lua

You can then try to run the examples:

$ cd golua/_example/
$ go run basic.go
$ go run alloc.go
$ go run panic.go
$ go run userdata.go

This library is configured using build tags. By default it will look for a library (or "shared object") called:

  • lua5.1 on Linux and macOS
  • lua on Windows
  • lua-5.1 on FreeBSD

If this doesn't work -tags luadash5.1 can be used to force lua-5.1, and -tags llua can be used to force lua.

If you want to statically link to liblua.a you can do that with -tags luaa. Luajit can also be used by specifying -tags luajit.

The library uses lua5.1 by default but also supports lua5.2 by specifying -tags lua52, lua5.3 by specifying -tags lua53, and lua5.4 by specifying -tags lua54.

QUICK START

Create a new Virtual Machine with:

L := lua.NewState()
L.OpenLibs()
defer L.Close()

Lua's Virtual Machine is stack based, you can call lua functions like this:

// push "print" function on the stack
L.GetGlobal("print")
// push the string "Hello World!" on the stack
L.PushString("Hello World!")
// call print with one argument, expecting no results
L.Call(1, 0)

Of course this isn't very useful, more useful is executing lua code from a file or from a string:

// executes a string of lua code
err := L.DoString("...")
// executes a file
err = L.DoFile(filename)

You will also probably want to publish go functions to the virtual machine, you can do it by:

func adder(L *lua.State) int {
	a := L.ToInteger(1)
	b := L.ToInteger(2)
	L.PushInteger(a + b)
	return 1 // number of return values
}

func main() {
	L := lua.NewState()
	defer L.Close()
	L.OpenLibs()

	L.Register("adder", adder)
	L.DoString("print(adder(2, 2))")
}

ON ERROR HANDLING

Lua's exceptions are incompatible with Go, golua works around this incompatibility by setting up protected execution environments in lua.State.DoString, lua.State.DoFile and lua.State.Call and turning every exception into a Go panic.

This means that:

  1. In general you can't do any exception handling from Lua, pcall and xpcall are renamed to unsafe_pcall and unsafe_xpcall. They are only safe to be called from Lua code that never calls back to Go. Use at your own risk.

  2. The call to lua.State.Error, present in previous versions of this library, has been removed as it is nonsensical

  3. Method calls on a newly created lua.State happen in an unprotected environment, if Lua throws an exception as a result your program will be terminated. If this is undesirable perform your initialization like this:

func LuaStateInit(L *lua.State) int {
	… initialization goes herereturn 0
}

…
L.PushGoFunction(LuaStateInit)
err := L.Call(0, 0)
…

ON THREADS AND COROUTINES

'lua.State' is not thread safe, but the library itself is. Lua's coroutines exist but (to my knowledge) have never been tested and are likely to encounter the same problems that errors have, use at your own peril.

ODDS AND ENDS

  • If you want to build against lua5.2, lua5.3, or lua5.4 use the build tags lua52, lua53, or lua54 respectively.
  • Compiling from source yields only a static link library (liblua.a), you can either produce the dynamic link library on your own or use the luaa build tag.

LUAJIT

To link with luajit-2.0.x, you can use CGO_CFLAGS and CGO_LDFLAGS environment variables

$ CGO_CFLAGS=`pkg-config luajit --cflags`
$ CGO_LDFLAGS=`pkg-config luajit --libs-only-L`
$ go get -f -u -tags luajit github.com/aarzilli/golua/lua

CONTRIBUTORS

  • Adam Fitzgerald (original author)
  • Alessandro Arzilli
  • Steve Donovan
  • Harley Laue
  • James Nurmi
  • Ruitao
  • Xushiwei
  • Isaint
  • hsinhoyeh
  • Viktor Palmkvist
  • HongZhen Peng
  • Admin36
  • Pierre Neidhardt (@Ambrevar)
  • HuangWei (@huangwei1024)
  • Adam Saponara

SEE ALSO

  • Luar is a reflection layer on top of golua API providing a simplified way to publish go functions to a Lua VM.
  • lunatico is a reflection layer that allows you to push and read Go values to a Lua VM without understanding the Lua stack.
  • Golua unicode is an extension library that adds unicode support to golua and replaces lua regular expressions with re2.

Licensing

GoLua is released under the MIT license. Please see the LICENSE file for more information.

Lua is Copyright (c) Lua.org, PUC-Rio. All rights reserved.

golua's People

Contributors

aarzilli avatar acd avatar adsr avatar afitz avatar ambrevar avatar b2ku avatar edolphin-ydf avatar elegios avatar fiatjaf avatar flier avatar hirochachacha avatar hongzhen avatar huangwei1024 avatar losinggeneration avatar nwidger avatar ptxmac avatar shanemhansen avatar simerax avatar superrxan avatar xushiwei avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

golua's Issues

can't build golua, got compile error

got compile error:

go get -u -tags llua github.com/aarzilli/golua/lua

github.com/aarzilli/golua/lua

golua.go:10: error: enumerator value for __cgo_enum__0' not integer constant golua.go:12: error: enumerator value for__cgo_enum__1' not integer constant
golua.go:14: error: enumerator value for __cgo_enum__2' not integer constant golua.go:16: error: enumerator value for__cgo_enum__3' not integer constant
golua.go:18: error: enumerator value for __cgo_enum__4' not integer constant golua.go:20: error: enumerator value for__cgo_enum__5' not integer constant
golua.go:22: error: syntax error before "lua_State"
golua.go:24: error: syntax error before "char"
golua.go:26: warning: initialization makes integer from pointer without a cast
golua.go:27: warning: initialization makes integer from pointer without a cast
golua.go:28: warning: initialization makes integer from pointer without a cast
golua.go:29: warning: initialization makes integer from pointer without a cast
golua.go:30: warning: initialization makes integer from pointer without a cast
golua.go:31: warning: initialization makes integer from pointer without a cast
golua.go:32: error: syntax error before ',' token

Error stack/tracebacks?

Hi there!

little disclaimer first: I'm not terribly familiar with go. I'm trying to take a look around how to use lua with go. I've opened a similar issue with Shopify/go-lua#87 because I had the same problem with (missing) tracebacks.

I'm struggling a bit on how to get proper tracebacks for errors.

Giving this hello.lua file containing:

print("Hello World")

function foo()
  print("Hello, I'm foo!")
  bar()
end

foo()

…run with lua hello.lua gives me:

Hello World
Hello, I'm foo!
lua: hello.lua:5: attempt to call global 'bar' (a nil value)
stack traceback:
	hello.lua:5: in function 'foo'
	hello.lua:8: in main chunk
	[C]: in ?

With golua used in file.go:

package main

import "../lua"
import "fmt"

func main() {
	L := lua.NewState()
	defer L.Close()
	L.OpenLibs()

	err := L.DoFile("hello.lua")

	fmt.Printf("%v\n", err)
}

…run with go run file.go gives me:

Hello World
Hello, I'm foo!
hello.lua:5: attempt to call global 'bar' (a nil value)

How can I get a comparable traceback with golua? Something that can be presented to a user. Are there more examples somewhere?

undefined reference issue

when i run go get -u -tags llua github.com/aarzilli/golua/lua,the result is the ld report many undefined reference.such as below:

/usr/local/lib/liblua.a(lvm.o): In function Arith': lvm.c:(.text+0x485): undefined reference topow'
lvm.c:(.text+0x4b4): undefined reference to floor' /usr/local/lib/liblua.a(lvm.o): In functionluaV_execute':
lvm.c:(.text+0x22c1): undefined reference to floor' lvm.c:(.text+0x23de): undefined reference topow'
/usr/local/lib/liblua.a(lmathlib.o): In function math_tan': lmathlib.c:(.text+0x9f): undefined reference totan'
/usr/local/lib/liblua.a(lmathlib.o): In function math_tanh': lmathlib.c:(.text+0xcf): undefined reference totanh'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sqrt': lmathlib.c:(.text+0x11c): undefined reference tosqrt'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sin': lmathlib.c:(.text+0x13f): undefined reference tosin'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sinh': lmathlib.c:(.text+0x16f): undefined reference tosinh'
/usr/local/lib/liblua.a(lmathlib.o): In function math_floor': lmathlib.c:(.text+0x29f): undefined reference tofloor'
/usr/local/lib/liblua.a(lmathlib.o): In function math_random': lmathlib.c:(.text+0x3be): undefined reference tofloor'
lmathlib.c:(.text+0x406): undefined reference to floor' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_pow':
lmathlib.c:(.text+0x48a): undefined reference to pow' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_log':
lmathlib.c:(.text+0x50f): undefined reference to log' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_log10':
lmathlib.c:(.text+0x53f): undefined reference to log10' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_fmod':
lmathlib.c:(.text+0x666): undefined reference to fmod' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_exp':
lmathlib.c:(.text+0x67f): undefined reference to exp' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_cos':
lmathlib.c:(.text+0x6af): undefined reference to cos' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_cosh':
lmathlib.c:(.text+0x6df): undefined reference to cosh' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_ceil':
lmathlib.c:(.text+0x70f): undefined reference to ceil' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_atan':
lmathlib.c:(.text+0x73f): undefined reference to atan' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_atan2':
lmathlib.c:(.text+0x78a): undefined reference to atan2' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_asin':
lmathlib.c:(.text+0x7bf): undefined reference to asin' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_acos':
lmathlib.c:(.text+0x7ef): undefined reference to acos' /usr/local/lib/liblua.a(loadlib.o): In functionll_loadfunc':
loadlib.c:(.text+0x878): undefined reference to dlsym' loadlib.c:(.text+0x8d1): undefined reference todlopen'
loadlib.c:(.text+0x8e9): undefined reference to dlerror' loadlib.c:(.text+0x900): undefined reference todlerror'
/usr/local/lib/liblua.a(loadlib.o): In function gctm': loadlib.c:(.text+0xcbc): undefined reference todlclose'
/usr/local/lib/liblua.a(lcode.o): In function codearith': lcode.c:(.text+0x1118): undefined reference topow'
lcode.c:(.text+0x1140): undefined reference to `floor'
collect2: ld returned 1 exit status

what shoud i do?

process is terminated when there is a lua error

Can I modify the function "callEx" in lua.go to remove C.GOLUA_DEFAULT_MSGHANDLER?
like this:
...
//L.GetGlobal(C.GOLUA_DEFAULT_MSHANDLER)
//erridex := L.GetTop() - nargs - 1
//L.Insert(erridx)
r := L.pcall(nargs, nresults, 0)
//L.Remove(erridx)
...

If I don't use any error handling function in "pcall", would there be any problem?
I tried, seems OK without terminated. But I don't understand.

Building for 5.3

OS: Arch Linux
Lua version: 5.3.4

Building for 5.3 with the go install -tags llua command, I get the following error:

github.com/aarzilli/golua/lua
# github.com/aarzilli/golua/lua
In file included from ./lua.h:16:0,
                 from ./golua.go:6,
                 from $WORK/github.com/aarzilli/golua/lua/_obj/_cgo_export.c:3:
./luaconf.h:192:34: fatal error: lua5.3-deb-multiarch.h: No such file or directory
 #include "lua5.3-deb-multiarch.h"
                                  ^

It works if I comment the deb related lines in luaconf.h:

/* This defines DEB_HOST_MULTIARCH */
// #include "lua5.3-deb-multiarch.h"

#define LUA_ROOT	"/usr/local/"
#define LUA_ROOT2	"/usr/"
#define LUA_LDIR	LUA_ROOT "share/lua/" LUA_VDIR "/"
#define LUA_LDIR2	LUA_ROOT2 "share/lua/" LUA_VDIR "/"
#define LUA_CDIR	LUA_ROOT "lib/lua/" LUA_VDIR "/"
// #define LUA_CDIR2	LUA_ROOT2 "lib/" DEB_HOST_MULTIARCH "/lua/" LUA_VDIR "/"
#define LUA_CDIR3	LUA_ROOT2 "lib/lua/" LUA_VDIR "/"

Compared to the 5.2 branch, there are header files both in lua/ and in lua/lua/. Why is it so? What are the differences?

Why not using the system headers by the way? If I try removing the embedded headers in lua/, I get the following error:

github.com/aarzilli/golua/lua
# github.com/aarzilli/golua/lua
/tmp/go-build411086781/github.com/aarzilli/golua/lua/_obj/lua.cgo2.o: In function `_cgo_1901af7180ba_Cfunc_lua_insert':
./cgo-gcc-prolog:594: undefined reference to `lua_insert'
/tmp/go-build411086781/github.com/aarzilli/golua/lua/_obj/lua.cgo2.o: In function `_cgo_1901af7180ba_Cfunc_lua_remove':
./cgo-gcc-prolog:957: undefined reference to `lua_remove'
/tmp/go-build411086781/github.com/aarzilli/golua/lua/_obj/lua.cgo2.o: In function `_cgo_1901af7180ba_Cfunc_lua_replace':
./cgo-gcc-prolog:971: undefined reference to `lua_replace'
/tmp/go-build411086781/github.com/aarzilli/golua/lua/_obj/c-golua.o: In function `callback_function':
./c-golua.c:77: undefined reference to `lua_remove'
collect2: error: ld returned 1 exit status

Could you enlighten me here?

exitsyscall: syscall frame is no longer valid

Hi,

I'm encountering the following panic:

fatal error: exitsyscall: syscall frame is no longer valid
    runtime stack:
    runtime.throw(0xfacd50, 0x2d)
	$GOROOT/src/runtime/panic.go:596 +0x95
    runtime.exitsyscall.func1()
	$GOROOT/src/runtime/proc.go:2587 +0x36
    runtime.systemstack(0x7fc0ea7fbe88)
	$GOROOT/src/runtime/asm_amd64.s:327 +0x79
    runtime.mstart()
	$GOROOT/src/runtime/proc.go:1132
    goroutine 2857675810 [syscall, locked to thread]:
    runtime.cgocall(0xdfbe60, 0xc4370a51a8, 0xfaa4fd)
	$GOROOT/src/runtime/cgocall.go:131 +0xe2 fp=0xc4370a5168 sp=0xc4370a5128
    golua/lua._Cfunc_lua_pushlstring(0x7f7a9004ef60, 0x7fc0e0265490, 0xa)
	golua/lua/_obj/_cgo_gotypes.go:1154 +0x45 fp=0xc4370a51a8 sp=0xc4370a5168
    golua/lua.(*State).PushString.func2(0x7f7a9004ef60, 0x7fc0e0265490, 0xa)
	$GOPATH/golua/lua/lua.go:385 +0x74 fp=0xc4370a51e0 sp=0xc4370a51a8
    golua/lua.(*State).PushString(0xc4662b8240, 0xf8f104, 0xa)
	$GOPATH/golua/lua/lua.go:385 +0x89 fp=0xc4370a5210 sp=0xc4370a51e0
OMITTED	INTERNAL LIB
    golua/lua.golua_callgofunction(0xc4662b8240, 0x39, 0xc400000008)
	$GOPATH/golua/lua/golua.go:73 +0x6d fp=0xc4370a5290 sp=0xc4370a5240
    golua/lua._cgoexpwrap_cea3daa1dadf_golua_callgofunction(0xc4662b8240, 0x39, 0x38994071e5)
	golua/lua/_obj/_cgo_gotypes.go:1568 +0x35 fp=0xc4370a52b8 sp=0xc4370a5290
    runtime.call32(0x0, 0x7fc0ea7fba38, 0x7fc0ea7fbad0, 0x18)
	$GOROOT/src/runtime/asm_amd64.s:514 +0x48 fp=0xc4370a52e8 sp=0xc4370a52b8
    runtime.cgocallbackg1(0x0)
	$GOROOT/src/runtime/cgocall.go:301 +0x19d fp=0xc4370a5360 sp=0xc4370a52e8
    runtime.cgocallbackg(0x0)
	$GOROOT/src/runtime/cgocall.go:184 +0x84 fp=0xc4370a53c8 sp=0xc4370a5360
    created by net/http.(*Server).Serve
	$GOROOT/src/net/http/server.go:2668 +0x2ce

From my basic understanding of this I think it might be related to setjmp/longjmp calls after which cgo calls into Go, which based on your comments in #53 and in several other places I understand is not allowed.

I'm pretty fuzzy on the details but I realize it's somewhat similar to this issue (mitchellh/go-mruby#49) which is fixed in (mitchellh/go-mruby#50).

Would love to know if you have an idea of what causes this and of a possible fix.

why unknow error occured?

Code:
if r != 0 {
if L.err == nil {
err = &LuaError{LUA_ERRERR, "unknow error", nil}
} else {
err = L.err
L.err = nil
}
}
When will this error happen?

lua5.3: `go test` fails

lua version: 5.3.4

Your latest commit e26bd17 introduced a regression and the tests don't pass anymore:

 go test -v -tags llua
=== RUN   TestGoStruct
--- PASS: TestGoStruct (0.00s)
=== RUN   TestCheckStringSuccess
--- PASS: TestCheckStringSuccess (0.00s)
=== RUN   TestCheckStringFail
--- PASS: TestCheckStringFail (0.00s)
=== RUN   TestPCallHidden
ciao
--- PASS: TestPCallHidden (0.00s)
=== RUN   TestCall
--- FAIL: TestCall (0.00s)
	lua_test.go:151: Wrong return value (2) got: <>
=== RUN   TestLikeBasic
Hello World!
--- FAIL: TestLikeBasic (0.00s)
	lua_test.go:195: Call to print returned error
=== RUN   TestLikeQuickstart
--- PASS: TestLikeQuickstart (0.00s)
=== RUN   TestLikeUserdata
--- PASS: TestLikeUserdata (0.00s)
=== RUN   TestStackTrace
--- PASS: TestStackTrace (0.00s)
=== RUN   TestIssue8
--- PASS: TestIssue8 (0.00s)
=== RUN   TestConv
--- PASS: TestConv (0.00s)
FAIL
exit status 1
FAIL	github.com/aarzilli/golua/lua	0.006s

Calling a Lua function in a file?

Hi,

I'm trying to call a Lua function defined in a file. But I keep getting "Error: attempt to call a nil value".

It seems like I might need to actually run the file after loading it ,but not sure how to do that. I didn't find any PCall().

My Go file:

package main

import "github.com/aarzilli/golua/lua"
import "fmt"

func main() {
    L := lua.NewState()
    defer L.Close()
    L.OpenLibs()
    L.LoadFile("hello.lua")

    // do i need to run the file here? how would i do that?

    L.GetField(lua.LUA_GLOBALSINDEX, "hello")       //push function
    err := L.Call(0,0)
    fmt.Printf("Error: %v\n", err)
}

My Lua file:

function hello()
  print("hello from Lua")
end

Thanks!

OS X Homebrew lua5.1 uses -llua5.1 not -llua

Now that homebrew moved lua to 5.2, they provide a lua5.1 pacakge. The issue is that the library is now called the same as it is on linux/windows, so we need to edit lua.go to get it to compile correctly.

Could we modify darwin to use 5.1 or add a 5.1 override similar to the llua/luaa tags that exist now?

C stack overflow in error handler

When calling a lua function that errors, the C stack is not cleaned up. If the lua function is called many times, it will eventually overflow the stack. Any further calls to the error handler result in the error "error in error handling" being returned.

This is the smallest test case I could come up with to reproduce it. I'm on Linux using lua 5.1.5 and the most recent version of golua.

error.go:

package main

import "github.com/aarzilli/golua/lua"
import "fmt"

func main() {
    L := lua.NewState()
    L.OpenLibs()
    if err := L.DoFile("error.lua"); err != nil {
        panic(err)
    }

    // 120 worked on my machine, might be different for you
    for i:=0; i<120; i++ {
        top := L.GetTop()
        L.GetGlobal("doError")
        err := L.Call(0, lua.LUA_MULTRET)
        if err != nil {
            fmt.Println("error:", err)
            fmt.Println("stack length:", len(L.StackTrace()))
            // fmt.Println("stack:", L.StackTrace())
        }
        L.SetTop(top)
    }
}

error.lua:

function doError()
    error("something bad")
end

Passing a Go string map to Lua?

Is there documentation anywhere on how to pass a Go string map to Lua?

I'm attempting to to use PushGoStruct(mymap) from Go, follow by a Call(1,0) and then access the map using mymap["somekey"] from the Lua function, but cannot make it work. I usually end up with errors like "reflect: call of reflect.Value.Elem on map Value".

panic: runtime error: cgo argument has Go pointer to Go pointer

version: go1.8.1
panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
github.com/aarzilli/golua/lua.newState.func1(0x5518030, 0x4b692a0, 0xc424492300)
/Users/xxx/workspace/src/xxx/src/github.com/aarzilli/golua/lua/lua.go:39 +0xb7
github.com/aarzilli/golua/lua.newState(0x5518030, 0xc400000002)
/Users/xxx/workspace/src/xxx/src/github.com/aarzilli/golua/lua/lua.go:40 +0x168
github.com/aarzilli/golua/lua.NewState(0x0)
/Users/xxx/workspace/src/xxx/src/github.com/aarzilli/golua/lua/lauxlib.go:168 +0x2f
github.com/stevedonovan/luar.Init(0xc428333d00)

PushGoFunction registers invalid type

I'm attempting to build a module loader in go and push the loader function into the lua_state package.preload. as follows:

func PreloadModule(LUA_STATE *lua.State, MOD_NAME string, LOADER_FUNC lua.LuaGoFunction) {
    LUA_STATE.GetField(lua.LUA_GLOBALSINDEX, "package")
    LUA_STATE.GetField(LUA_STATE.GetTop(), "preload")
    LUA_STATE.PushGoFunction(LOADER_FUNC)
    LUA_STATE.SetField(2, MOD_NAME)
}
...
PreloadModule(L, "mymodule", func(L *lua.State) int {
    fmt.Println('Hello From Require')
    return 0
})
...
require('mymodule')
main.lua:1: module 'mymodule' not found:

It appears functions get pushed into the lua_state as type userdata, and lua fails to call the package.preload entry as it does not see it as a callable function.

C API notes that C functions get pushed as type function http://pgl.yoyo.org/luai/i/lua_pushcfunction can we mimic this behavior with lua.PushGoFunction ?

Thanks!

golua have link error, running go 1.7.3

win64.env
CGO_ENABLED=1

link error:
lib/../lib/libntdll.a(dudjbs01971.o):(.idata$5+0x0): multiple definition of __imp_sqrt' d:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../../../x86_64-w64-mingw32/lib/../lib/libmsvcrt.a(dglbbs01052.o):(.idata$5+0x0): first defined here d:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../../../x86_64-w64-mingw32/lib/../lib/libntdll.a(dudjbs01968.o):(.idata$5+0x0): multiple definition of __imp_sin'
d:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../../../x86_64-w64-mingw32/lib/../lib/libmsvcrt.a(dglbbs01047.o):(.idata$5+0x0): first defined here
d:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.9.2/../../../../x86_64-w64-mingw32/lib/../lib/libntdll.a(dudjbs01966.o):(.idata$5+0x0): multiple definition of `__imp_pow'
who have this question? how to solve this question?

debug message

When something wrong happen, how can I get the error msg just like in lua shell? State.RaiseMsg is poor.

ToThread implementation

I did an implementation of ToThread. It appears to work, but I would glad to have it reviewed by someone with more experience. If it seems satisfactory, it might be pleasant to add it to golua.

In place https://github.com/aarzilli/golua/blob/master/lua/lua.go#L568 of the TODO, I wrote:

// lua_tothread
func (L *State) ToThread(index int) *State {
    s := &State{s: (*C.lua_State)(unsafe.Pointer(C.lua_tothread(L.s, C.int(index))))}
    registerGoState(s)
    return s
}

In particular, is the registerGoState(s) call the correct thing to do? I'm not at all certain. When I register fmt.Printf with one thread, invoking it calls MakeChan registered with the main vm, so it seems that wires are getting crossed. But that might just be a different bug elsewhere.

Lua 5.2

Lua 5.2 will probably be available in Wheezy (next Debian stable to be released this weekend), so it would be nice to be able to use the newest Lua version.

Support metatables for GoStruct

I'm trying to set a metatable to a GoStruct object to be able calling methods in the manner like obj:Foo().

Currently, testudata() doesn't allow me to do this, requiring the object metatable to be MT_GOINTERFACE or MT_GOFUNCTION.

I understand the idea of this check, and suggest extending it in the following manner:

if (!lua_rawequal(L, -1, -2))  /* not the same? */

    // Check the second-level metatable
    if (lua_getmetatable(L, -2)) {
        if (lua_rawequal(L, -2, -1)) {  /* equals! */
            lua_pop(L, 3);  /* cleanup */
            return p;
        }
        lua_pop(L, 1);
    }
    // end of new code

    p = NULL;
}
lua_pop(L, 2);  /* remove both metatables */
return p;

In addition, the setmetatable() call should be modified (as following), or a new function (e.g. SetGoStructMetaTable) may be introduced if you find this way more appropriate.

void clua_setmetatable(lua_State* L, unsigned int index)
{
    if (clua_isgostruct(index)) {
        // Set MT_GOINTERFACE as a second-level metatable for the user metatable
        luaL_getmetatable(L, MT_GOINTERFACE);
        lua_setmetatable(L,-2);
    }

    lua_setmetatable(L, index);
    return true;
}

Implement luaL_register

I'd like to register a Go library to be called from Lua:

test.lua

require "somelib"
somelib.SomeFunc(params...)

somelib.go

package somelib
func SomeFunc(params...)

relevant man docs

I'm not entirely sure how to get this to work. It seems that lua.Register isn't actually sending the function pointer down to the C api, but storing it locally and using the registry to call functions. How should this work using a library?

I'd like to help if you could point me in the right direction. Some explanation on how the registry works would be fantastic. I need this pretty soon, so I'll probably start working on this on Monday.

Method to raise Lua errors from Go code

Hi Alessandro,

In luar I have a need for a method like this so that I can raise Lua errors from Go.

 func (L *State) RaiseError(msg string) {
    L.Where(1)
    pos := L.ToString(-1)
    L.Pop(1)
    panic(&LuaError{0,pos + " " + msg,L.StackTrace()})
 }

Strictly speaking, all I need is a public LuaError 'constructor' (NewLuaError) since we cannot initialize the private fields of LuaError from outside the package:

func (L *State) NewLuaError(msg string) *LuaError {
   return &LuaError{0,msg,L.StackTrace()}
}

That would be the simplest and most flexible solution.

Unless I've missed something very obvious!

using the library from a vendor directory

Hi,

When I try to use this from a vendor directory I get:

vendor/github.com/aarzilli/golua/lua/golua.go:6:17: fatal error: lua.h: No such file or directory
#include <lua.h>
^
compilation terminated.

What I am doing wrong?

Thanks

How about add method to get *C.lua_State?

Thanks for your work on golua.
After look around the source, i found that there is no way to get the *C.lua_State.
Is it possible to export the member L.s for some special usage?
Eg: in order to void call from go to c many times, i'v writen some c api which accept lua_State* as a parameter( and some other params), but there is no way that i can access the L.s except modify the golua source code.

cannot find -llua5.1

[vagrant@lain example]$ go build basic.go 
# _/vagrant/develop/golua/lua
/usr/bin/ld: cannot find -llua5.1

centos lua5.1.4
how can i fix this error?

go1.2 warning

../github.com/aarzilli/golua/lua/c-golua.c:93:7: warning: initializing 'int *' with an expression of type 'unsigned int *' converts between pointers to integer types with different sign [-Wpointer-sign]
../github.com/aarzilli/golua/lua/c-golua.c:99:7: warning: initializing 'int *' with an expression of type 'unsigned int *' converts between pointers to integer types with different sign [-Wpointer-sign]
../github.com/aarzilli/golua/lua/c-golua.c:218:1: warning: control reaches end of non-void function [-Wreturn-type]

cannot run on windows

I 've compiled it on windows xp successfully, but when I run go test, error occured!

C:>go test github.com/aarzilli/golua/lua
unexpected fault address 0x4ac9d7
fatal error: fault
[signal 0xc0000005 code=0x1 addr=0x4ac9d7 pc=0x4ac9f5]

runtime stack:
invalid spdelta 339960 -1
runtime: unexpected return pc for x_cgo_thread_start called from 0x4ac9ed00
runtime.throw(0x61de3e)
D:/GoDev/golang/src/pkg/runtime/panic.c:464 +0x67
runtime.sigpanic()
D:/GoDev/golang/src/pkg/runtime/os_windows.c:340 +0xe1
invalid spdelta 339960 -1
runtime: unexpected return pc for x_cgo_thread_start called from 0x4ac9ed00
x_cgo_thread_start()
?:0 +0x1e

goroutine 1 [running]:
runtime.asmcgocall(0x4ac9d7, 0x2e2784)
D:/GoDev/golang/src/pkg/runtime/asm_386.s:585 +0x22 fp=0x2e277c
newm(0x417470, 0x0)
D:/GoDev/golang/src/pkg/runtime/proc.c:908 +0x8a fp=0x2e2798
runtime.main()
D:/GoDev/golang/src/pkg/runtime/proc.c:191 +0x3a fp=0x2e27cc
runtime.goexit()
D:/GoDev/golang/src/pkg/runtime/proc.c:1394 fp=0x2e27d0
FAIL github.com/aarzilli/golua/lua 0.469s

why hide pcall

void clua_hide_pcall(lua_State *L)
{
	lua_getglobal(L, "pcall");
	lua_setglobal(L, "unsafe_pcall");
	lua_pushnil(L);
	lua_setglobal(L, "pcall");

	lua_getglobal(L, "xpcall");
	lua_setglobal(L, "unsafe_xpcall");
	lua_pushnil(L);
	lua_setglobal(L, "xpcall");
}

why pcall and xpcall is unsafe ?

mulitple lua_state in each goroutine, will panic

func worker() {
	L := lua.NewState()
	defer L.Close()
	L.OpenLibs()
	L.DoFile("./test.lua")
}
func test() {
	count := 1000
	ch := make(chan int, count)
	for i := 0; i < count; i++ {
		go worker()
	}
        // wait all
}

if count < 500, it is ok. but bigger count, it will panic. so wired!

Incorrect type in second argument to CheckType

It should be LuaValType, as opposed to int. This is because the go-side of the library redefines the lua-side int constants representing the different lua types to be of type LuaValType (with underlying representation int).

go1.6 support

It looks like golua violates the go1.6 CGO pointer rules.

Test program:

L := lua.NewState()
L.OpenLibs()
defer L.Close()

output:

panic: runtime error: cgo argument has Go pointer to Go pointer

goroutine 1 [running]:
github.com/aarzilli/golua/lua.newState(0xdb8400, 0x0)
    /home/shansen/src/github.com/aarzilli/golua/lua/lua.go:41 +0x23e
github.com/aarzilli/golua/lua.NewState(0x7f1345e3b078)
    /home/shansen/src/github.com/aarzilli/golua/lua/lauxlib.go:169 +0x25
main.main()
    /home/shansen/src/$snip/main.go:8 +0x18
exit status 2

More info about the new rules here: https://tip.golang.org/doc/go1

4 byte per luastate memory leak

As part of making golua compatible with go1.6, a global, never shrinking array of luastate objects was addeed, with the note "leaks 4 bytes per lua state".
1074bd5

Any ideas on how to get around that?

Fatal error when a Lua error is raised in protected call

I know you already know about this issue, but I thought it'd be prudent to make an issue for it as well. Basically the issue boils down to a fatal error being generated in Go when Lua raises an error (setjmp/longjmp) from within a Go callback that was called within a PCall. Below is a minimal example illustrating the issue:

package main

import (
    "fmt"
    lua "github.com/aarzilli/golua/lua"
)

func Test(L *lua.State) int {
    L.CheckString(-1)

    return 0
}

func main() {
    l := lua.NewState()
    l.Register("test", Test)

    if l.LoadString("test()") == 0 {
        l.PCall(0, lua.LUA_MULTRET, 0)
    }

    fmt.Println("returned from pcall...")
}

This runs into the PCall and into Test where a Lua error is raised which then causes issues with Go getting back to where it needs to:

fatal error: runtime: bad defer entry in cgocallback

Cannot build on CentOS 7

Please notice that https://github.com/aarzilli/golua/blob/master/lua/lua.go#L9 cannot be build on CentOS 7.

The issue is with naming of lua*.pc file, which is used by pkg-config tool. Refer to https://code.google.com/p/grafx2/issues/detail?id=328 for similar discussion and some investigations. Not sure whether guys solved issue in their project, but I was not able to google any solution or another useful discussion on the topic either.

In the nutshell, different linux distros, have a habit to name this file differently:

  • Debian / Ubuntu - lua5.1.pc
  • Arch / CentOS / RedHat - lua.pc.

There is no build constraint for #cgo pseudo directive in Go comments to differentiate between linux distros.

Suggestion to pass "llua" tag in the closed #34 won't help, because execution won't reach line 11 where this tag checked as it fails at the line 9 where pkg-config invoked:

# pkg-config --cflags lua5.1
Package lua5.1 was not found in the pkg-config search path.
Perhaps you should add the directory containing `lua5.1.pc'
to the PKG_CONFIG_PATH environment variable
No package 'lua5.1' found
pkg-config: exit status 1

Only workaround for me was to do: sed -i -r -e "s/(#cgo .*)lua5.1(.*)/\1lua\2/" vendor/lua/lua.go in my build script, which is rather brittle and lame solution.

Probably, it's better to remove #cgo pkg-config directive at all, as it is broken for lua and provide flags via env variables or tags only.

lua.h not found

Golua gives a build error when trying to install it.
/usr/lib/go/src/pkg/github.com/aarzilli/golua/lua/c-golua.c:2 5c: No such file or directory: lua.h
While /usr/include/lua5.1/lua.h is present.
How can I check the include paths?
Should the #include in golua.c be
#include "lua/lua.h" in stead of #include <lua.h>?

go test crash on osx with luajit-2.1-beta3, unexpected SIGSEGV / SIGBUS on TestCheckStringFail

Golua looks pretty awesome. I hear people using with LuaJIT just fine, but I'm trying it for the first time and not having any luck. I built against luajit-2.1-beta3 on my mac, go1.91 and osx 10.12.5.

I tried both 64-bit and 32-bit builds. Both crash with fatal error: unexpected signal during runtime execution 64-bit complains of SIGSEGV. 32-bit complains of SIGBUS. Both are crashing on the TestCheckStringFail test.

64-bit crash:

jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ go test -v
go test -v
=== RUN   TestGoStruct
--- PASS: TestGoStruct (0.00s)
=== RUN   TestCheckStringSuccess
--- PASS: TestCheckStringSuccess (0.00s)
=== RUN   TestCheckStringFail
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x7fff091d3828 pc=0x7fff091d3828]

runtime stack:
runtime.throw(0x414fe08, 0x2a)
	/usr/local/go/src/runtime/panic.go:605 +0x95
runtime.sigpanic()
	/usr/local/go/src/runtime/signal_unix.go:351 +0x2b8

goroutine 7 [syscall, locked to thread]:
runtime.cgocall(0x40fee50, 0xc420049dc8, 0x40f0100)
	/usr/local/go/src/runtime/cgocall.go:132 +0xe4 fp=0xc420049d80 sp=0xc420049d40 pc=0x4003a14
github.com/glycerine/golua/lua._Cfunc_lua_pcall(0x4580378, 0xffffffff00000000, 0x1, 0x0)
	github.com/glycerine/golua/lua/_test/_obj_test/_cgo_gotypes.go:1102 +0x4d fp=0xc420049dc8 sp=0xc420049d80 pc=0x40f562d
github.com/glycerine/golua/lua.(*State).pcall.func1(0x4580378, 0xffffffff00000000, 0x1, 0x1)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:175 +0x78 fp=0xc420049e00 sp=0xc420049dc8 pc=0x40fb878
github.com/glycerine/golua/lua.(*State).pcall(0xc4200667c0, 0x0, 0xffffffffffffffff, 0x1, 0x40fd7e0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:175 +0x49 fp=0xc420049e30 sp=0xc420049e00 pc=0x40f8d19
github.com/glycerine/golua/lua.(*State).callEx(0xc4200667c0, 0x0, 0xffffffffffffffff, 0x4302501, 0x0, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:194 +0xd7 fp=0xc420049ea8 sp=0xc420049e30 pc=0x40f8e17
github.com/glycerine/golua/lua.(*State).Call(0xc4200667c0, 0x0, 0xffffffffffffffff, 0x0, 0xffffd8ee)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:207 +0x44 fp=0xc420049ee8 sp=0xc420049ea8 pc=0x40f9044
github.com/glycerine/golua/lua.(*State).DoString(0xc4200667c0, 0x4148e9c, 0x7, 0x41516d8, 0x406b1d6)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lauxlib.go:107 +0x190 fp=0xc420049f58 sp=0xc420049ee8 pc=0x40f8540
github.com/glycerine/golua/lua.TestCheckStringFail(0xc4200a22d0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua_test.go:75 +0xb0 fp=0xc420049fa8 sp=0xc420049f58 pc=0x40f2bb0
testing.tRunner(0xc4200a22d0, 0x41516e0)
	/usr/local/go/src/testing/testing.go:746 +0xd0 fp=0xc420049fd0 sp=0xc420049fa8 pc=0x40b78a0
runtime.goexit()
	/usr/local/go/src/runtime/asm_amd64.s:2337 +0x1 fp=0xc420049fd8 sp=0xc420049fd0 pc=0x4058c51
created by testing.(*T).Run
	/usr/local/go/src/testing/testing.go:789 +0x2de

goroutine 1 [chan receive]:
testing.(*T).Run(0xc4200a2000, 0x414afdb, 0x13, 0x41516e0, 0x406b101)
	/usr/local/go/src/testing/testing.go:790 +0x2fc
testing.runTests.func1(0xc4200a2000)
	/usr/local/go/src/testing/testing.go:1004 +0x64
testing.tRunner(0xc4200a2000, 0xc42005bde0)
	/usr/local/go/src/testing/testing.go:746 +0xd0
testing.runTests(0xc42000c0c0, 0x41fcfe0, 0xa, 0xa, 0x41ff4a0)
	/usr/local/go/src/testing/testing.go:1002 +0x2d8
testing.(*M).Run(0xc42005bf18, 0xc42005bf70)
	/usr/local/go/src/testing/testing.go:921 +0x111
main.main()
	github.com/glycerine/golua/lua/_test/_testmain.go:62 +0xdb
exit status 2
FAIL	github.com/glycerine/golua/lua	0.158s
jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ ls

32-bit crash:

jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ ./lua.test -test.v
./lua.test -test.v
=== RUN   TestGoStruct
--- PASS: TestGoStruct (0.00s)
=== RUN   TestCheckStringSuccess
--- PASS: TestCheckStringSuccess (0.00s)
=== RUN   TestCheckStringFail
fatal error: unexpected signal during runtime execution
[signal SIGBUS: bus error code=0x2 addr=0x43e18b0 pc=0x43e18b0]

runtime stack:
runtime.throw(0x41bb8c5, 0x2a)
	/usr/local/go/src/runtime/panic.go:605 +0x76
runtime.sigpanic()
	/usr/local/go/src/runtime/signal_unix.go:351 +0x252

goroutine 7 [syscall, locked to thread]:
runtime.cgocall(0x4113530, 0x15233e84, 0x4188940)
	/usr/local/go/src/runtime/cgocall.go:132 +0x7b fp=0x15233e5c sp=0x15233e44 pc=0x4003ffb
github.com/glycerine/golua/lua._Cfunc_lua_pcall(0x43de1c0, 0x0, 0xffffffff, 0x1, 0x0)
	github.com/glycerine/golua/lua/_test/_obj_test/_cgo_gotypes.go:1100 +0x39 fp=0x15233e84 sp=0x15233e5c pc=0x410ae49
github.com/glycerine/golua/lua.(*State).pcall.func1(0x43de1c0, 0x0, 0xffffffff, 0x1, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:175 +0x6d fp=0x15233ea4 sp=0x15233e84 pc=0x4110dfd
github.com/glycerine/golua/lua.(*State).pcall(0x15260640, 0x0, 0xffffffff, 0x1, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:175 +0x3f fp=0x15233ec0 sp=0x15233ea4 pc=0x410e4af
github.com/glycerine/golua/lua.(*State).callEx(0x15260640, 0x0, 0xffffffff, 0x4700001, 0x0, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:194 +0xd0 fp=0x15233f0c sp=0x15233ec0 pc=0x410e5a0
github.com/glycerine/golua/lua.(*State).Call(0x15260640, 0x0, 0xffffffff, 0x0, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua.go:207 +0x40 fp=0x15233f30 sp=0x15233f0c pc=0x410e770
github.com/glycerine/golua/lua.(*State).DoString(0x15260640, 0x41b4923, 0x7, 0x0, 0x0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lauxlib.go:112 +0x159 fp=0x15233f70 sp=0x15233f30 pc=0x410dab9
github.com/glycerine/golua/lua.TestCheckStringFail(0x152a01b0)
	/Users/jaten/go/src/github.com/glycerine/golua/lua/lua_test.go:75 +0x9d fp=0x15233fb0 sp=0x15233f70 pc=0x4107fad
testing.tRunner(0x152a01b0, 0x41bd0a0)
	/usr/local/go/src/testing/testing.go:746 +0xce fp=0x15233fe8 sp=0x15233fb0 pc=0x40c0dde
runtime.goexit()
	/usr/local/go/src/runtime/asm_386.s:1635 +0x1 fp=0x15233fec sp=0x15233fe8 pc=0x4052111
created by testing.(*T).Run
	/usr/local/go/src/testing/testing.go:789 +0x3b0

goroutine 1 [chan receive]:
testing.(*T).Run(0x152a01b0, 0x41b6a9f, 0x13, 0x41bd0a0, 0x96f00)
	/usr/local/go/src/testing/testing.go:790 +0x3c9
testing.runTests.func1(0x152a0000)
	/usr/local/go/src/testing/testing.go:1004 +0xa9
testing.tRunner(0x152a0000, 0x15255e84)
	/usr/local/go/src/testing/testing.go:746 +0xce
testing.runTests(0x1520c060, 0x4255740, 0xa, 0xa, 0x100)
	/usr/local/go/src/testing/testing.go:1002 +0x28a
testing.(*M).Run(0x1527e0f0, 0x0)
	/usr/local/go/src/testing/testing.go:921 +0x26f
main.main()
	github.com/glycerine/golua/lua/_test/_testmain.go:62 +0x99
jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ file ./lua.test 
file ./lua.test 
./lua.test: Mach-O executable i386
jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ go version 
go version 
go version go1.9.1 darwin/amd64
jaten@Jasons-MacBook-Pro ~/go/src/github.com/glycerine/golua/lua (master) $ 

I'm using the latest master branch, 24fe5b5 which is tip currently.

go build fail with Lua 5.1 built from source code

my environment is ubuntu 12.04 and golang version is 1.2.
if my lua 5.1 is installed from apt-get, your golua library works well for me.
for example:
sudo apt-get install lua5.1
go get -u github.com/aarzilli/golua/lua
and go build, which works well.

but something goes wrong if I installed lua5.1 from source code.
What I have done is :
cd lua-5.1
make linux ( because I use linux platform)
make linux install

when I am doing go build on your package:
I have encountered the following error message:
github.com/aarzilli/golua/lua
/usr/local/lib/liblua.a(lvm.o): In function Arith': lvm.c:(.text+0x475): undefined reference topow'
lvm.c:(.text+0x4a4): undefined reference to floor' /usr/local/lib/liblua.a(lvm.o): In functionluaV_execute':
lvm.c:(.text+0x222f): undefined reference to floor' lvm.c:(.text+0x232b): undefined reference topow'
/usr/local/lib/liblua.a(lmathlib.o): In function math_tan': lmathlib.c:(.text+0x9f): undefined reference totan'
/usr/local/lib/liblua.a(lmathlib.o): In function math_tanh': lmathlib.c:(.text+0xcf): undefined reference totanh'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sqrt': lmathlib.c:(.text+0x11c): undefined reference tosqrt'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sin': lmathlib.c:(.text+0x13f): undefined reference tosin'
/usr/local/lib/liblua.a(lmathlib.o): In function math_sinh': lmathlib.c:(.text+0x16f): undefined reference tosinh'
/usr/local/lib/liblua.a(lmathlib.o): In function math_floor': lmathlib.c:(.text+0x29f): undefined reference tofloor'
/usr/local/lib/liblua.a(lmathlib.o): In function math_random': lmathlib.c:(.text+0x3bf): undefined reference tofloor'
lmathlib.c:(.text+0x407): undefined reference to floor' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_pow':
lmathlib.c:(.text+0x48a): undefined reference to pow' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_log':
lmathlib.c:(.text+0x50f): undefined reference to log' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_log10':
lmathlib.c:(.text+0x53f): undefined reference to log10' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_fmod':
lmathlib.c:(.text+0x65c): undefined reference to fmod' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_exp':
lmathlib.c:(.text+0x67f): undefined reference to exp' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_cos':
lmathlib.c:(.text+0x6af): undefined reference to cos' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_cosh':
lmathlib.c:(.text+0x6df): undefined reference to cosh' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_ceil':
lmathlib.c:(.text+0x70f): undefined reference to ceil' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_atan':
lmathlib.c:(.text+0x73f): undefined reference to atan' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_atan2':
lmathlib.c:(.text+0x78a): undefined reference to atan2' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_asin':
lmathlib.c:(.text+0x7bf): undefined reference to asin' /usr/local/lib/liblua.a(lmathlib.o): In functionmath_acos':
lmathlib.c:(.text+0x7ef): undefined reference to acos' /usr/local/lib/liblua.a(loadlib.o): In functionll_loadfunc':
loadlib.c:(.text+0x878): undefined reference to dlsym' loadlib.c:(.text+0x8c9): undefined reference todlerror'
loadlib.c:(.text+0x8e9): undefined reference to dlopen' loadlib.c:(.text+0x8ff): undefined reference todlerror'
/usr/local/lib/liblua.a(loadlib.o): In function gctm': loadlib.c:(.text+0xc8c): undefined reference todlclose'
/usr/local/lib/liblua.a(lcode.o): In function codearith': lcode.c:(.text+0x1018): undefined reference topow'
lcode.c:(.text+0x1040): undefined reference to `floor'
collect2: error: ld returned 1 exit status

After done some search, I founded that the following modification (add ldl and lm libraries) can be compiled without any error message:
diff --git a/lua/lua.go b/lua/lua.go
index 3704e13..06088f6 100644
--- a/lua/lua.go
+++ b/lua/lua.go
@@ -8,7 +8,7 @@ package lua
/*
#cgo CFLAGS: -Ilua
#cgo llua LDFLAGS: -llua
-#cgo linux,!llua LDFLAGS: -llua5.1
+#cgo linux,!llua LDFLAGS: -llua -ldl -lm
#cgo darwin LDFLAGS: -llua
#cgo freebsd LDFLAGS: -llua

should I submit a pull request for it? any suggestions? thanks

Build on Darwin failed

$ go get -v -v github.com/stevedonovan/luar
github.com/aarzilli/golua/lua
# github.com/aarzilli/golua/lua
ld: library not found for -llua
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Environment: Darwin 10.9.4

Lua was installed from brew:

$ brew upgrade lua
Error: lua-5.1.5 already installed

$ brew upgrade luabind
Error: luabind-0.9.1 already installed

lib files exists:

$ cd /usr/local/lib
$ ls  *lua*
liblua.5.1.5.dylib liblua.5.1.dylib   libluabind.dylib

go run alloc.go error.

$ go run alloc.go
SIGABRT: abort
PC=0x356c035a19
signal arrived during cgo execution

runtime.asmcgocall(0x4052c0, 0x7f067d191e60)
/home/edward/dev/go-dev/src/pkg/runtime/asm_amd64.s:528 +0x2d fp=0x7f067d191e00
runtime.cgocall(0x4052c0, 0x7f067d191e60)
/home/edward/dev/go-dev/src/pkg/runtime/cgocall.c:166 +0x15b fp=0x7f067d191e48
github.com/aarzilli/golua/lua._Cfunc_clua_setgostate(0xc210030840, 0x4b79c0, 0xc21003e080)
github.com/aarzilli/golua/lua/_obj/_cgo_defun.c:245 +0x31 fp=0x7f067d191e60
github.com/aarzilli/golua/lua.newState(0xc210030840, 0xc210030840)
/home/edward/projects/goprj/gopath/src/github.com/aarzilli/golua/lua/lua.go:38 +0xf4 fp=0x7f067d191eb8
github.com/aarzilli/golua/lua.NewStateAlloc(0x4e4ca8, 0x0)
/home/edward/projects/goprj/gopath/src/github.com/aarzilli/golua/lua/lua.go:328 +0x4a fp=0x7f067d191ed0
main.main()
/home/edward/projects/goprj/golua/src/alloc.go:36 +0x6d fp=0x7f067d191f48
runtime.main()
/home/edward/dev/go-dev/src/pkg/runtime/proc.c:201 +0x113 fp=0x7f067d191fa0
runtime.goexit()
/home/edward/dev/go-dev/src/pkg/runtime/proc.c:1332 fp=0x7f067d191fa8

goroutine 2 [runnable]:
runtime.MHeap_Scavenger()
/home/edward/dev/go-dev/src/pkg/runtime/mheap.c:438
runtime.goexit()
/home/edward/dev/go-dev/src/pkg/runtime/proc.c:1332
created by runtime.main
/home/edward/dev/go-dev/src/pkg/runtime/proc.c:168

goroutine 3 [syscall]:
runtime.goexit()
/home/edward/dev/go-dev/src/pkg/runtime/proc.c:1332

rax 0x0
rbx 0xc210030840
rcx 0xffffffffffffffff
rdx 0x6
rdi 0x362c
rsi 0x362c
rbp 0xc210030950
rsp 0x7fff0aaaf608
r8 0x789c40
r9 0x356c140d10
r10 0x8
r11 0x202
r12 0xc210021288
r13 0xc210043010
r14 0x7f067d224b60
r15 0xc210043010
rip 0x356c035a19
rflags 0x202
cs 0x33
fs 0x0
gs 0x0
exit status 2

branch:lua5.2

Runtime crash using LuaJIT

I have tried using golua with LuaJIT 2.0.4 without success due to the unit tests crashing. I tired both static and dynamic lyncing and confirmed with ldd on the output of go test -c. As soon as I return to using standard Lua the tests pass. Here is an example crash while using dynamic linking:

fatal error: unexpected signal during runtime execution
[signal 0xb code=0x1 addr=0x7fe7838180a0 pc=0x7fe7838180a0]

runtime stack:
runtime.throw(0x5da100, 0x2a)
    /home/user/go/src/runtime/panic.go:527 +0x90
runtime.sigpanic()
    /home/user/go/src/runtime/sigpanic_unix.go:12 +0x5a

goroutine 7 [syscall, locked to thread]:
runtime.cgocall(0x405c70, 0xc82002ddb0, 0x0)
    /home/user/go/src/runtime/cgocall.go:120 +0x11b fp=0xc82002dd68 sp=0xc82002dd38
tb/golua/lua._Cfunc_lua_pcall(0x40f11378, 0xffffffff00000000, 0x1, 0x0)
    ??:0 +0x39 fp=0xc82002ddb0 sp=0xc82002dd68
tb/golua/lua.(*State).pcall(0xc820010a40, 0x0, 0xffffffffffffffff, 0x1, 0x884060)
    /home/user/corp/src/tb/golua/lua/lua.go:182 +0x45 fp=0xc82002ddd8 sp=0xc82002ddb0
tb/golua/lua.(*State).callEx(0xc820010a40, 0x0, 0xffffffffffffffff, 0x1579001, 0x0, 0x0)
    /home/user/corp/src/tb/golua/lua/lua.go:201 +0xfb fp=0xc82002de48 sp=0xc82002ddd8
tb/golua/lua.(*State).Call(0xc820010a40, 0x0, 0xffffffffffffffff, 0x0, 0x0)
    /home/user/corp/src/tb/golua/lua/lua.go:214 +0x48 fp=0xc82002de80 sp=0xc82002de48
tb/golua/lua.(*State).DoString(0xc820010a40, 0x5a3900, 0x7, 0x0, 0x0)
    /home/user/corp/src/tb/golua/lua/lauxlib.go:106 +0x1c7 fp=0xc82002dee8 sp=0xc82002de80
tb/golua/lua.TestCheckStringFail(0xc82009c120)
    /home/user/corp/src/tb/golua/lua/lua_test.go:71 +0xbf fp=0xc82002df78 sp=0xc82002dee8
testing.tRunner(0xc82009c120, 0x8742d0)
    /home/user/go/src/testing/testing.go:456 +0x98 fp=0xc82002dfb0 sp=0xc82002df78
runtime.goexit()
    /home/user/go/src/runtime/asm_amd64.s:1696 +0x1 fp=0xc82002dfb8 sp=0xc82002dfb0
created by testing.RunTests
    /home/user/go/src/testing/testing.go:561 +0x86d

goroutine 1 [chan receive]:
testing.RunTests(0x5eca30, 0x8742a0, 0xa, 0xa, 0x1)
    /home/user/go/src/testing/testing.go:562 +0x8ad
testing.(*M).Run(0xc82004fef8, 0xc82000a6c0)
    /home/user/go/src/testing/testing.go:494 +0x70
main.main()
    tb/golua/lua/_test/_testmain.go:72 +0x116

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
    /home/user/go/src/runtime/asm_amd64.s:1696 +0x1

re-allocation bug

Thanks for golua. Generally it is fantastic.

I hit the following bug, causing a firey crash in my program.

https://github.com/aarzilli/golua/blob/master/lua/lua.go#L80

newSlice := make([]interface{}, index, cap(L.registry)*2)

should read

newSlice := make([]interface{}, index, (1+cap(L.registry))*2)

because when cap is 0, the slice doesn't grow. Since 2 * 0 is still 0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.