pax_global_header00006660000000000000000000000064133157070040014512gustar00rootroot0000000000000052 comment=2518c8179c6de77f760f5a82df43f6f9a8ad8657 golang-layeh-gopher-luar-1.0.4/000077500000000000000000000000001331570700400163065ustar00rootroot00000000000000golang-layeh-gopher-luar-1.0.4/.gitignore000066400000000000000000000000101331570700400202650ustar00rootroot00000000000000/.idea/ golang-layeh-gopher-luar-1.0.4/LICENSE000066400000000000000000000405261331570700400173220ustar00rootroot00000000000000Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor's Contribution. 1.3. "Contribution" means Covered Software of a particular Contributor. 1.4. "Covered Software" means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. "Incompatible With Secondary Licenses" means (a) that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or (b) that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. "Executable Form" means any form of the work other than Source Code Form. 1.7. "Larger Work" means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. "License" means this document. 1.9. "Licensable" means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. "Modifications" means any of the following: (a) any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or (b) any new file in Source Code Form that contains any Covered Software. 1.11. "Patent Claims" of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. "Secondary License" means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. "Source Code Form" means the form of the work preferred for making modifications. 1.14. "You" (or "Your") means an individual or a legal entity exercising rights under this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, "control" means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions -------------------------------- 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: (a) under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and (b) under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: (a) for any code that a Contributor has removed from Covered Software; or (b) for infringements caused by: (i) Your and any other third party's modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or (c) under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities ------------------- 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients' rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: (a) such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and (b) You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients' rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation --------------------------------------------------- If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination -------------- 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. ************************************************************************ * * * 6. Disclaimer of Warranty * * ------------------------- * * * * Covered Software is provided under this License on an "as is" * * basis, without warranty of any kind, either expressed, implied, or * * statutory, including, without limitation, warranties that the * * Covered Software is free of defects, merchantable, fit for a * * particular purpose or non-infringing. The entire risk as to the * * quality and performance of the Covered Software is with You. * * Should any Covered Software prove defective in any respect, You * * (not any Contributor) assume the cost of any necessary servicing, * * repair, or correction. This disclaimer of warranty constitutes an * * essential part of this License. No use of any Covered Software is * * authorized under this License except under this disclaimer. * * * ************************************************************************ ************************************************************************ * * * 7. Limitation of Liability * * -------------------------- * * * * Under no circumstances and under no legal theory, whether tort * * (including negligence), contract, or otherwise, shall any * * Contributor, or anyone who distributes Covered Software as * * permitted above, be liable to You for any direct, indirect, * * special, incidental, or consequential damages of any character * * including, without limitation, damages for lost profits, loss of * * goodwill, work stoppage, computer failure or malfunction, or any * * and all other commercial damages or losses, even if such party * * shall have been informed of the possibility of such damages. This * * limitation of liability shall not apply to liability for death or * * personal injury resulting from such party's negligence to the * * extent applicable law prohibits such limitation. Some * * jurisdictions do not allow the exclusion or limitation of * * incidental or consequential damages, so this exclusion and * * limitation may not apply to You. * * * ************************************************************************ 8. Litigation ------------- Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party's ability to bring cross-claims or counter-claims. 9. Miscellaneous ---------------- This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License --------------------------- 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice ------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - "Incompatible With Secondary Licenses" Notice --------------------------------------------------------- This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. golang-layeh-gopher-luar-1.0.4/Makefile000066400000000000000000000002011331570700400177370ustar00rootroot00000000000000coverage-report: go test -coverprofile=coverage.out go tool cover -html=coverage.out rm coverage.out .PHONY: coverage-report golang-layeh-gopher-luar-1.0.4/README.md000066400000000000000000000021371331570700400175700ustar00rootroot00000000000000# gopher-luar [![GoDoc](https://godoc.org/layeh.com/gopher-luar?status.svg)](https://godoc.org/layeh.com/gopher-luar) gopher-luar simplifies data passing to and from [gopher-lua](https://github.com/yuin/gopher-lua). Example usage: package luar_test import ( "fmt" "github.com/yuin/gopher-lua" "layeh.com/gopher-luar" ) type User struct { Name string token string } func (u *User) SetToken(t string) { u.token = t } func (u *User) Token() string { return u.token } const script = ` print("Hello from Lua, " .. u.Name .. "!") u:SetToken("12345") ` func Example_basic() { L := lua.NewState() defer L.Close() u := &User{ Name: "Tim", } L.SetGlobal("u", luar.New(L, u)) if err := L.DoString(script); err != nil { panic(err) } fmt.Println("Lua set your token to:", u.Token()) // Output: // Hello from Lua, Tim! // Lua set your token to: 12345 } ## License MPL 2.0 ## Author Tim Cooper () golang-layeh-gopher-luar-1.0.4/array.go000066400000000000000000000045651331570700400177650ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func arrayIndex(L *lua.LState) int { ref, mt := check(L, 1) ref = reflect.Indirect(ref) key := L.CheckAny(2) switch converted := key.(type) { case lua.LNumber: index := int(converted) if index < 1 || index > ref.Len() { L.ArgError(2, "index out of range") } val := ref.Index(index - 1) if (val.Kind() == reflect.Struct || val.Kind() == reflect.Array) && val.CanAddr() { val = val.Addr() } L.Push(New(L, val.Interface())) case lua.LString: if fn := mt.method(string(converted)); fn != nil { L.Push(fn) return 1 } return 0 default: L.ArgError(2, "must be a number or string") } return 1 } func arrayPtrIndex(L *lua.LState) int { ref, mt := check(L, 1) ref = ref.Elem() key := L.CheckAny(2) switch converted := key.(type) { case lua.LNumber: index := int(converted) if index < 1 || index > ref.Len() { L.ArgError(2, "index out of range") } val := ref.Index(index - 1) if (val.Kind() == reflect.Struct || val.Kind() == reflect.Array) && val.CanAddr() { val = val.Addr() } L.Push(New(L, val.Interface())) case lua.LString: if fn := mt.method(string(converted)); fn != nil { L.Push(fn) return 1 } mt = MT(L, ref.Interface()) if fn := mt.method(string(converted)); fn != nil { L.Push(fn) return 1 } return 0 default: L.ArgError(2, "must be a number or string") } return 1 } func arrayPtrNewIndex(L *lua.LState) int { ref, _ := check(L, 1) ref = ref.Elem() index := L.CheckInt(2) value := L.CheckAny(3) if index < 1 || index > ref.Len() { L.ArgError(2, "index out of range") } hint := ref.Type().Elem() val, err := lValueToReflect(L, value, hint, nil) if err != nil { L.ArgError(3, err.Error()) } ref.Index(index - 1).Set(val) return 0 } func arrayLen(L *lua.LState) int { ref, _ := check(L, 1) ref = reflect.Indirect(ref) L.Push(lua.LNumber(ref.Len())) return 1 } func arrayCall(L *lua.LState) int { ref, _ := check(L, 1) ref = reflect.Indirect(ref) i := 0 fn := func(L *lua.LState) int { if i >= ref.Len() { return 0 } item := ref.Index(i).Interface() L.Push(lua.LNumber(i + 1)) L.Push(New(L, item)) i++ return 2 } L.Push(L.NewFunction(fn)) return 1 } func arrayEq(L *lua.LState) int { ref1, _ := check(L, 1) ref2, _ := check(L, 2) L.Push(lua.LBool(ref1.Interface() == ref2.Interface())) return 1 } golang-layeh-gopher-luar-1.0.4/array_test.go000066400000000000000000000031651331570700400210170ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) type TestArrayOneString [1]string func (o TestArrayOneString) Get() string { return o[0] } func Test_array(t *testing.T) { L := lua.NewState() defer L.Close() type Elem struct { V [2]string } var elem Elem elem.V[0] = "Hello" elem.V[1] = "World" var arr TestArrayOneString arr[0] = "Test" L.SetGlobal("e", New(L, &elem)) L.SetGlobal("arr", New(L, arr)) testReturn(t, L, `return #e.V, e.V[1], e.V[2]`, "2", "Hello", "World") testReturn(t, L, `e.V[1] = "World"; e.V[2] = "Hello"`) testReturn(t, L, `return #e.V, e.V[1], e.V[2]`, "2", "World", "Hello") testReturn(t, L, `return #arr, arr[1]`, "1", "Test") testReturn(t, L, `return arr:Get()`, "Test") testError(t, L, `e.V[1] = nil`, "cannot use nil as type string") } func Test_array_iterator(t *testing.T) { L := lua.NewState() defer L.Close() a := [...]string{"x", "y"} L.SetGlobal("a", New(L, a)) L.SetGlobal("ap", New(L, &a)) testReturn(t, L, `local itr = a(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "x", "2", "y") testReturn(t, L, `local itr = ap(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "x", "2", "y") } func Test_array_eq(t *testing.T) { L := lua.NewState() defer L.Close() a := [...]string{"x", "y"} b := [...]string{"x", "y"} L.SetGlobal("a", New(L, a)) L.SetGlobal("ap", New(L, &a)) L.SetGlobal("b", New(L, b)) L.SetGlobal("bp", New(L, &b)) testReturn(t, L, `return a == b`, "true") testReturn(t, L, `return a ~= b`, "false") testReturn(t, L, `return ap == nil`, "false") testReturn(t, L, `return ap == bp`, "false") } golang-layeh-gopher-luar-1.0.4/cache.go000066400000000000000000000117371331570700400177110ustar00rootroot00000000000000package luar import ( "container/list" "reflect" "github.com/yuin/gopher-lua" ) func addMethods(L *lua.LState, c *Config, vtype reflect.Type, tbl *lua.LTable, ptrReceiver bool) { for i := 0; i < vtype.NumMethod(); i++ { method := vtype.Method(i) if method.PkgPath != "" { continue } namesFn := c.MethodNames if namesFn == nil { namesFn = defaultMethodNames } fn := funcWrapper(L, method.Func, ptrReceiver) for _, name := range namesFn(vtype, method) { tbl.RawSetString(name, fn) } } } func addFields(L *lua.LState, c *Config, vtype reflect.Type, tbl *lua.LTable) { type element struct { Type reflect.Type Index []int } queue := list.New() queue.PushFront(element{ Type: vtype, }) namesFn := c.FieldNames if namesFn == nil { namesFn = defaultFieldNames } for queue.Len() > 0 { e := queue.Back() elem := e.Value.(element) vtype := elem.Type fields: for i := 0; i < vtype.NumField(); i++ { field := vtype.Field(i) if field.PkgPath != "" && !field.Anonymous { continue } names := namesFn(vtype, field) for _, key := range names { if tbl.RawGetString(key) != lua.LNil { continue fields } } ud := L.NewUserData() ud.Value = append(elem.Index[:len(elem.Index):len(elem.Index)], i) for _, key := range names { tbl.RawSetString(key, ud) } if field.Anonymous { t := field.Type if field.Type.Kind() != reflect.Struct { if field.Type.Kind() != reflect.Ptr || field.Type.Elem().Kind() != reflect.Struct { continue } t = field.Type.Elem() } queue.PushFront(element{ Type: t, Index: append(elem.Index[:len(elem.Index):len(elem.Index)], i), }) } } queue.Remove(e) } } func getMetatable(L *lua.LState, vtype reflect.Type) *lua.LTable { config := GetConfig(L) if v := config.regular[vtype]; v != nil { return v } var ( mt *lua.LTable methods = L.CreateTable(0, vtype.NumMethod()) ) switch vtype.Kind() { case reflect.Array: mt = L.CreateTable(0, 7) mt.RawSetString("__index", L.NewFunction(arrayIndex)) mt.RawSetString("__len", L.NewFunction(arrayLen)) mt.RawSetString("__call", L.NewFunction(arrayCall)) mt.RawSetString("__eq", L.NewFunction(arrayEq)) addMethods(L, config, vtype, methods, false) case reflect.Chan: mt = L.CreateTable(0, 8) mt.RawSetString("__index", L.NewFunction(chanIndex)) mt.RawSetString("__len", L.NewFunction(chanLen)) mt.RawSetString("__eq", L.NewFunction(chanEq)) mt.RawSetString("__call", L.NewFunction(chanCall)) mt.RawSetString("__unm", L.NewFunction(chanUnm)) addMethods(L, config, vtype, methods, false) case reflect.Map: mt = L.CreateTable(0, 7) mt.RawSetString("__index", L.NewFunction(mapIndex)) mt.RawSetString("__newindex", L.NewFunction(mapNewIndex)) mt.RawSetString("__len", L.NewFunction(mapLen)) mt.RawSetString("__call", L.NewFunction(mapCall)) addMethods(L, config, vtype, methods, false) case reflect.Slice: mt = L.CreateTable(0, 8) mt.RawSetString("__index", L.NewFunction(sliceIndex)) mt.RawSetString("__newindex", L.NewFunction(sliceNewIndex)) mt.RawSetString("__len", L.NewFunction(sliceLen)) mt.RawSetString("__call", L.NewFunction(sliceCall)) mt.RawSetString("__add", L.NewFunction(sliceAdd)) addMethods(L, config, vtype, methods, false) case reflect.Struct: mt = L.CreateTable(0, 6) fields := L.CreateTable(0, vtype.NumField()) addFields(L, config, vtype, fields) mt.RawSetString("fields", fields) mt.RawSetString("__index", L.NewFunction(structIndex)) mt.RawSetString("__eq", L.NewFunction(structEq)) addMethods(L, config, vtype, methods, false) case reflect.Ptr: switch vtype.Elem().Kind() { case reflect.Array: mt = L.CreateTable(0, 10) mt.RawSetString("__index", L.NewFunction(arrayPtrIndex)) mt.RawSetString("__newindex", L.NewFunction(arrayPtrNewIndex)) mt.RawSetString("__call", L.NewFunction(arrayCall)) // same as non-pointer mt.RawSetString("__len", L.NewFunction(arrayLen)) // same as non-pointer case reflect.Struct: mt = L.CreateTable(0, 8) mt.RawSetString("__index", L.NewFunction(structPtrIndex)) mt.RawSetString("__newindex", L.NewFunction(structPtrNewIndex)) default: mt = L.CreateTable(0, 7) mt.RawSetString("__index", L.NewFunction(ptrIndex)) } mt.RawSetString("__eq", L.NewFunction(ptrEq)) mt.RawSetString("__pow", L.NewFunction(ptrPow)) mt.RawSetString("__unm", L.NewFunction(ptrUnm)) addMethods(L, config, vtype, methods, true) default: panic("unexpected kind " + vtype.Kind().String()) } mt.RawSetString("__tostring", L.NewFunction(tostring)) mt.RawSetString("__metatable", lua.LString("gopher-luar")) mt.RawSetString("methods", methods) config.regular[vtype] = mt return mt } func getTypeMetatable(L *lua.LState, t reflect.Type) *lua.LTable { config := GetConfig(L) if v := config.types; v != nil { return v } mt := L.CreateTable(0, 2) mt.RawSetString("__call", L.NewFunction(typeCall)) mt.RawSetString("__eq", L.NewFunction(typeEq)) config.types = mt return mt } golang-layeh-gopher-luar-1.0.4/chan.go000066400000000000000000000025721331570700400175540ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func chanIndex(L *lua.LState) int { _, mt := check(L, 1) key := L.CheckString(2) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } return 0 } func chanLen(L *lua.LState) int { ref, _ := check(L, 1) L.Push(lua.LNumber(ref.Len())) return 1 } func chanEq(L *lua.LState) int { ref1, _ := check(L, 1) ref2, _ := check(L, 2) L.Push(lua.LBool(ref1.Pointer() == ref2.Pointer())) return 1 } func chanCall(L *lua.LState) int { ref, _ := check(L, 1) switch L.GetTop() { // Receive case 1: if ref.Type().ChanDir()&reflect.RecvDir == 0 { L.ArgError(1, "receive from send-only type "+ref.Type().String()) } value, ok := ref.Recv() if ok { L.Push(New(L, value.Interface())) L.Push(lua.LTrue) } else { L.Push(lua.LNil) L.Push(lua.LFalse) } return 2 // Send case 2: if ref.Type().ChanDir()&reflect.SendDir == 0 { L.ArgError(1, "send to receive-only type "+ref.Type().String()) } value := L.CheckAny(2) hint := ref.Type().Elem() convertedValue, err := lValueToReflect(L, value, hint, nil) if err != nil { L.ArgError(2, err.Error()) } ref.Send(convertedValue) return 0 default: L.RaiseError("expecting 1 or 2 arguments, got %d", L.GetTop()) panic("never reaches") } } func chanUnm(L *lua.LState) int { ref, _ := check(L, 1) ref.Close() return 0 } golang-layeh-gopher-luar-1.0.4/chan_test.go000066400000000000000000000023761331570700400206150ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_chan(t *testing.T) { L := lua.NewState() defer L.Close() ch := make(chan string) go func() { ch <- "Tim" name, ok := <-ch if name != "John" || !ok { t.Fatal("invalid value") } close(ch) }() L.SetGlobal("ch", New(L, ch)) testReturn(t, L, `return ch()`, "Tim", "true") testReturn(t, L, `ch("John")`) testReturn(t, L, `return ch()`, "nil", "false") } type TestChanString chan string func (*TestChanString) Test() string { return "TestChanString.Test" } func (TestChanString) Test2() string { return "TestChanString.Test2" } func Test_chan_pointermethod(t *testing.T) { L := lua.NewState() defer L.Close() a := make(TestChanString) b := &a L.SetGlobal("b", New(L, b)) testReturn(t, L, `return b:Test()`, "TestChanString.Test") testReturn(t, L, `return b:Test2()`, "TestChanString.Test2") } func Test_chan_invaliddirection(t *testing.T) { L := lua.NewState() defer L.Close() ch := make(chan string) L.SetGlobal("send", New(L, (chan<- string)(ch))) testError(t, L, `send()`, "receive from send-only type chan<- string") L.SetGlobal("receive", New(L, (<-chan string)(ch))) testError(t, L, `receive("hello")`, "send to receive-only type <-chan string") } golang-layeh-gopher-luar-1.0.4/config.go000066400000000000000000000035731331570700400201120ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) // Config is used to define luar behaviour for a particular *lua.LState. type Config struct { // The name generating function that defines under which names Go // struct fields will be accessed. // // If nil, the default behaviour is used: // - if the "luar" tag of the field is "", the field name and its name // with a lowercase first letter is returned // - if the tag is "-", no name is returned (i.e. the field is not // accessible) // - for any other tag value, that value is returned FieldNames func(s reflect.Type, f reflect.StructField) []string // The name generating function that defines under which names Go // methods will be accessed. // // If nil, the default behaviour is used: // - the method name and its name with a lowercase first letter MethodNames func(t reflect.Type, m reflect.Method) []string regular map[reflect.Type]*lua.LTable types *lua.LTable } func newConfig() *Config { return &Config{ regular: make(map[reflect.Type]*lua.LTable), } } // GetConfig returns the luar configuration options for the given *lua.LState. func GetConfig(L *lua.LState) *Config { const registryKey = "github.com/layeh/gopher-luar" registry := L.Get(lua.RegistryIndex).(*lua.LTable) lConfig, ok := registry.RawGetString(registryKey).(*lua.LUserData) if !ok { lConfig = L.NewUserData() lConfig.Value = newConfig() registry.RawSetString(registryKey, lConfig) } return lConfig.Value.(*Config) } func defaultFieldNames(s reflect.Type, f reflect.StructField) []string { const tagName = "luar" tag := f.Tag.Get(tagName) if tag == "-" { return nil } if tag != "" { return []string{tag} } return []string{ f.Name, getUnexportedName(f.Name), } } func defaultMethodNames(t reflect.Type, m reflect.Method) []string { return []string{ m.Name, getUnexportedName(m.Name), } } golang-layeh-gopher-luar-1.0.4/config_test.go000066400000000000000000000027171331570700400211500ustar00rootroot00000000000000package luar import ( "reflect" "testing" "github.com/yuin/gopher-lua" "strings" ) func Test_config(t *testing.T) { L := lua.NewState() defer L.Close() config := GetConfig(L) if config == nil { t.Fatal("expecting non-nil config") } if config.FieldNames != nil { t.Fatal("expected config.FieldName to be nil") } if config.MethodNames != nil { t.Fatal("expected config.MethodName to be nil") } } func Test_config_fieldnames(t *testing.T) { L := lua.NewState() defer L.Close() config := GetConfig(L) config.FieldNames = func(s reflect.Type, f reflect.StructField) []string { return []string{strings.ToLower(f.Name)} } type S struct { Name string Age int `luar:"AGE"` } s := S{ Name: "Tim", Age: 89, } L.SetGlobal("s", New(L, &s)) testReturn(t, L, `return s.Name`, `nil`) testReturn(t, L, `return s.name`, `Tim`) testReturn(t, L, `return s.AGE`, `nil`) testReturn(t, L, `return s.age`, `89`) } type TestConfigMethodnames []string func (t TestConfigMethodnames) Len() int { return len(t) } func Test_config_methodnames(t *testing.T) { L := lua.NewState() defer L.Close() config := GetConfig(L) config.MethodNames = func(s reflect.Type, m reflect.Method) []string { return []string{strings.ToLower(m.Name) + "gth"} } v := TestConfigMethodnames{ "hello", "world", } L.SetGlobal("v", New(L, v)) testError(t, L, `return v:len()`, `attempt to call a non-function object`) testReturn(t, L, `return v:length()`, `2`) } golang-layeh-gopher-luar-1.0.4/doc.go000066400000000000000000000032701331570700400174040ustar00rootroot00000000000000// Package luar simplifies data passing to and from gopher-lua. // (https://github.com/yuin/gopher-lua). // // Go to Lua conversions // // See documentation of New function. // // Lua to Go conversions // // Lua types are automatically converted to match the output Go type (e.g. // setting a struct field from Lua). // // lua.LNil can be converted to any channel, func, interface, map, pointer, // slice, unsafepointer, or uintptr value. // // lua.LBool values are converted to bool. // // lua.LNumber values are converted to float64. // // lua.LString values are converted to string. // // lua.LChannel values are converted to lua.LChannel. // // *lua.LTable values can be converted to an array, slice, map, struct, or // struct pointer. If the table is being assigned with no type information (i.e. // to an interface{}), the converted value will have the type // map[interface{}]interface{}. // // The Value field of *lua.LUserData values are converted rather than the // *lua.LUserData value itself. // // *lua.LState values are converted to *lua.LState. // // *lua.LFunction values are converted to Go functions. If the function is // being assigned with no type information (i.e. to a interface{}), the function // will have the signature func(...interface{}) []interface{}. The arguments // and return values will be converted using the standard luar conversion rules. // // Thread safety // // This package accesses and modifies the Lua state's registry. This happens // when functions like New are called, and potentially when luar-created values // are used. It is your responsibility to ensure that concurrent access of the // state's registry does not happen. package luar // import "layeh.com/gopher-luar" golang-layeh-gopher-luar-1.0.4/example_test.go000066400000000000000000000012141331570700400213250ustar00rootroot00000000000000package luar_test import ( "fmt" "github.com/yuin/gopher-lua" "layeh.com/gopher-luar" ) type User struct { Name string token string } func (u *User) SetToken(t string) { u.token = t } func (u *User) Token() string { return u.token } const script = ` print("Hello from Lua, " .. u.Name .. "!") u:SetToken("12345") ` func Example_basic() { L := lua.NewState() defer L.Close() u := &User{ Name: "Tim", } L.SetGlobal("u", luar.New(L, u)) if err := L.DoString(script); err != nil { panic(err) } fmt.Println("Lua set your token to:", u.Token()) // Output: // Hello from Lua, Tim! // Lua set your token to: 12345 } golang-layeh-gopher-luar-1.0.4/examples_test.go000066400000000000000000000014131331570700400215110ustar00rootroot00000000000000package luar import ( "github.com/yuin/gopher-lua" ) func ExampleLState() { const code = ` print(sum(1, 2, 3, 4, 5)) ` L := lua.NewState() defer L.Close() sum := func(L *LState) int { total := 0 for i := 1; i <= L.GetTop(); i++ { total += L.CheckInt(i) } L.Push(lua.LNumber(total)) return 1 } L.SetGlobal("sum", New(L, sum)) if err := L.DoString(code); err != nil { panic(err) } // Output: // 15 } func ExampleNewType() { L := lua.NewState() defer L.Close() type Song struct { Title string Artist string } L.SetGlobal("Song", NewType(L, Song{})) if err := L.DoString(` s = Song() s.Title = "Montana" s.Artist = "Tycho" print(s.Artist .. " - " .. s.Title) `); err != nil { panic(err) } // Output: // Tycho - Montana } golang-layeh-gopher-luar-1.0.4/func.go000066400000000000000000000065301331570700400175740ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) // LState is an wrapper for gopher-lua's LState. It should be used when you // wish to have a function/method with the standard "func(*lua.LState) int" // signature. type LState struct { *lua.LState } var ( refTypeLStatePtr = reflect.TypeOf(&LState{}) refTypeLuaLValue = reflect.TypeOf((*lua.LValue)(nil)).Elem() refTypeInt = reflect.TypeOf(int(0)) refTypeEmptyIface = reflect.TypeOf((*interface{})(nil)).Elem() ) func getFunc(L *lua.LState) (ref reflect.Value, refType reflect.Type) { ref = L.Get(lua.UpvalueIndex(1)).(*lua.LUserData).Value.(reflect.Value) refType = ref.Type() return } func isPtrReceiverMethod(L *lua.LState) bool { return bool(L.Get(lua.UpvalueIndex(2)).(lua.LBool)) } func funcIsBypass(t reflect.Type) bool { if t.NumIn() == 1 && t.NumOut() == 1 && t.In(0) == refTypeLStatePtr && t.Out(0) == refTypeInt { return true } if t.NumIn() == 2 && t.NumOut() == 1 && t.In(1) == refTypeLStatePtr && t.Out(0) == refTypeInt { return true } return false } func funcBypass(L *lua.LState) int { ref, refType := getFunc(L) convertedPtr := false var receiver reflect.Value var ud lua.LValue luarState := LState{L} args := make([]reflect.Value, 0, 2) if refType.NumIn() == 2 { receiverHint := refType.In(0) ud = L.Get(1) var err error if isPtrReceiverMethod(L) { receiver, err = lValueToReflect(L, ud, receiverHint, &convertedPtr) } else { receiver, err = lValueToReflect(L, ud, receiverHint, nil) } if err != nil { L.ArgError(1, err.Error()) } args = append(args, receiver) L.Remove(1) } args = append(args, reflect.ValueOf(&luarState)) ret := ref.Call(args)[0].Interface().(int) if convertedPtr { ud.(*lua.LUserData).Value = receiver.Elem().Interface() } return ret } func funcRegular(L *lua.LState) int { ref, refType := getFunc(L) top := L.GetTop() expected := refType.NumIn() variadic := refType.IsVariadic() if !variadic && top != expected { L.RaiseError("invalid number of function arguments (%d expected, got %d)", expected, top) } if variadic && top < expected-1 { L.RaiseError("invalid number of function arguments (%d or more expected, got %d)", expected-1, top) } convertedPtr := false var receiver reflect.Value var ud lua.LValue args := make([]reflect.Value, top) for i := 0; i < L.GetTop(); i++ { var hint reflect.Type if variadic && i >= expected-1 { hint = refType.In(expected - 1).Elem() } else { hint = refType.In(i) } var arg reflect.Value var err error if i == 0 && isPtrReceiverMethod(L) { ud = L.Get(1) v := ud arg, err = lValueToReflect(L, v, hint, &convertedPtr) if err != nil { L.ArgError(1, err.Error()) } receiver = arg } else { v := L.Get(i + 1) arg, err = lValueToReflect(L, v, hint, nil) if err != nil { L.ArgError(i+1, err.Error()) } } args[i] = arg } ret := ref.Call(args) if convertedPtr { ud.(*lua.LUserData).Value = receiver.Elem().Interface() } for _, val := range ret { L.Push(New(L, val.Interface())) } return len(ret) } func funcWrapper(L *lua.LState, fn reflect.Value, isPtrReceiverMethod bool) *lua.LFunction { up := L.NewUserData() up.Value = fn if funcIsBypass(fn.Type()) { return L.NewClosure(funcBypass, up, lua.LBool(isPtrReceiverMethod)) } return L.NewClosure(funcRegular, up, lua.LBool(isPtrReceiverMethod)) } golang-layeh-gopher-luar-1.0.4/func_test.go000066400000000000000000000104031331570700400206250ustar00rootroot00000000000000package luar import ( "reflect" "testing" "github.com/yuin/gopher-lua" ) func Test_func_variableargs(t *testing.T) { L := lua.NewState() defer L.Close() fn := func(str string, extra ...int) { switch str { case "a": if len(extra) != 3 || extra[0] != 1 || extra[1] != 2 || extra[2] != 3 { t.Fatalf("unexpected variable arguments: %v", extra) } case "b": if len(extra) != 0 { t.Fatalf("unexpected variable arguments: %v", extra) } case "c": if len(extra) != 1 || extra[0] != 4 { t.Fatalf("unexpected variable arguments: %v", extra) } } } L.SetGlobal("fn", New(L, fn)) testReturn(t, L, `return fn("a", 1, 2, 3)`) testReturn(t, L, `return fn("b")`) testReturn(t, L, `return fn("c", 4)`) } func Test_func_structarg(t *testing.T) { L := lua.NewState() defer L.Close() tim := &StructTestPerson{ Name: "Tim", } fn := func(p *StructTestPerson) string { return "Hello, " + p.Name } L.SetGlobal("person", New(L, tim)) L.SetGlobal("getHello", New(L, fn)) testReturn(t, L, `return getHello(person)`, "Hello, Tim") } func Test_func_nilreference(t *testing.T) { L := lua.NewState() defer L.Close() var fn func() L.SetGlobal("fn", New(L, fn)) testReturn(t, L, `return fn`, "nil") } func Test_func_arrayarg(t *testing.T) { L := lua.NewState() defer L.Close() arr := [3]int{1, 2, 3} fn := func(val [3]int) { if val != arr { t.Fatalf("expecting %v, got %v", arr, val) } } L.SetGlobal("fn", New(L, fn)) L.SetGlobal("arr", New(L, arr)) testReturn(t, L, `return fn(arr)`) } func Test_func_luareturntype(t *testing.T) { L := lua.NewState() defer L.Close() fn := func(x ...float64) *lua.LTable { tbl := L.NewTable() for i := len(x) - 1; i >= 0; i-- { tbl.Insert(len(x)-i, lua.LNumber(x[i])) } return tbl } L.SetGlobal("fn", New(L, fn)) testReturn( t, L, ` local t = {} for _, x in ipairs(fn(1, 2, 3)) do table.insert(t, x) end return t[1], t[2], t[3]`, "3", "2", "1", ) testReturn( t, L, ` local t = {} for _, x in ipairs(fn()) do table.insert(t, x) end return t[1]`, "nil", ) } type TestLuaFuncRef struct { F1 *lua.LFunction } func Test_func_luafuncref(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestLuaFuncRef{} L.SetGlobal("e", New(L, e)) testReturn( t, L, ` e.F1 = function(str) return "Hello World", 123 end `, ) L.Push(e.F1) L.Call(0, 2) if L.GetTop() != 2 || L.Get(1).String() != "Hello World" || L.Get(2).String() != "123" { t.Fatal("incorrect return values") } } type TestFuncCall struct { Fn func(a string) (string, int) Fn2 func(a string, b ...int) string } func Test_func_luafunccall(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestFuncCall{} L.SetGlobal("x", New(L, e)) testReturn( t, L, ` i = 0 x.Fn = function(str) i = i + 1 return ">" .. str .. "<", i end x.Fn2 = function(str, a, b, c) if type(a) == "number" and type(b) == "number" and type(c) == "number" then return str end return "" end `, ) if str, i := e.Fn("A"); str != ">A<" || i != 1 { t.Fatal("unexpected return values") } if str, i := e.Fn("B"); str != ">B<" || i != 2 { t.Fatal("unexpected return values") } if val := e.Fn2("hello", 1, 2); val != "" { t.Fatal("unexpected return value") } if val := e.Fn2("hello", 1, 2, 3); val != "hello" { t.Fatal("unexpected return value") } if L.GetTop() != 0 { t.Fatalf("expecting GetTop to return 0, got %d", L.GetTop()) } } func Test_func_argerror(t *testing.T) { L := lua.NewState() defer L.Close() fn := func(v uint8) { } L.SetGlobal("fn", New(L, fn)) testError(t, L, `fn("hello world")`, "bad argument #1 to fn (cannot use hello world (type lua.LString) as type uint8)") } func Test_func_conversionstack(t *testing.T) { L := lua.NewState() defer L.Close() var fn interface{} L.SetGlobal("fn", New(L, &fn)) if err := L.DoString(`_ = fn ^ function() return "hello", true, 123 end`); err != nil { t.Fatal(err) } callable, ok := fn.(func(...interface{}) []interface{}) if !ok { t.Fatal("invalid function signature") } values := callable() expected := []interface{}{ string("hello"), bool(true), float64(123), } if !reflect.DeepEqual(expected, values) { t.Fatalf("expected return %#v, got %#v", expected, values) } } golang-layeh-gopher-luar-1.0.4/helpers_test.go000066400000000000000000000031721331570700400213410ustar00rootroot00000000000000package luar import ( "runtime/debug" "strconv" "strings" "testing" "github.com/yuin/gopher-lua" ) type StructTestPerson struct { Name string Age int Friend *StructTestPerson LastAddSum int } func (p StructTestPerson) Hello() string { return "Hello, " + p.Name } func (p StructTestPerson) String() string { return p.Name + " (" + strconv.Itoa(p.Age) + ")" } func (p *StructTestPerson) AddNumbers(L *LState) int { sum := 0 for i := L.GetTop(); i >= 1; i-- { sum += L.CheckInt(i) } L.Push(lua.LString(p.Name + " counts: " + strconv.Itoa(sum))) p.LastAddSum = sum return 1 } func (p *StructTestPerson) IncreaseAge() { p.Age++ } func testReturn(t *testing.T, L *lua.LState, code string, values ...string) { top := L.GetTop() if err := L.DoString(code); err != nil { t.Fatalf("%s\n\n%s", err, debug.Stack()) } valid := true newTop := L.GetTop() if newTop-top != len(values) { valid = false } else { for i, expect := range values { // TODO: strong typing val := L.Get(top + i + 1).String() if val != expect { valid = false } } } if !valid { got := make([]string, newTop-top) for i := 0; i < len(got); i++ { got[i] = L.Get(top + i + 1).String() } t.Fatalf("bad return values: expecting %#v, got %#v\n\n%s", values, got, debug.Stack()) } L.SetTop(top) } func testError(t *testing.T, L *lua.LState, code, error string) { err := L.DoString(code) if err == nil { t.Fatalf("expecting error, got nil\n\n%s", debug.Stack()) } if s := err.Error(); strings.Index(s, error) == -1 { t.Fatalf("error substring '%s' not found in '%s'\n\n%s", error, s, debug.Stack()) } } golang-layeh-gopher-luar-1.0.4/luar.go000066400000000000000000000330441331570700400176040ustar00rootroot00000000000000package luar import ( "fmt" "reflect" "github.com/yuin/gopher-lua" ) // New creates and returns a new lua.LValue for the given value. Values are // converted in the following manner: // // A nil value (untyped, or a nil channel, function, map, pointer, or slice) is // converted to lua.LNil. // // A lua.LValue value is returned without conversion. // // Boolean values are converted to lua.LBool. // // String values are converted to lua.LString. // // Real numeric values (ints, uints, and floats) are converted to lua.LNumber. // // Functions are converted to *lua.LFunction. When called from Lua, Lua values // are converted to Go using the rules described in the package documentation, // and Go return values converted to Lua values using the rules described by // New. // // If a function has the signature: // func(*LState) int // *LState defined in this package, not in lua // The argument and return value conversions described above are skipped, and // the function is called with the arguments passed on the Lua stack. Return // values are pushed to the stack and the number of return values is returned // from the function. // // Arrays, channels, maps, pointers, slices, and structs are all converted to // *lua.LUserData with its Value field set to value. The userdata's metatable // is set to a table generated for value's type. The type's method set is // callable from the Lua type. If the type implements the fmt.Stringer // interface, that method will be used when the value is passed to the Lua // tostring function. // // With arrays, the # operator returns the array's length. Array elements can // be accessed with the index operator (array[index]). Calling an array // (array()) returns an iterator over the array that can be used in a for loop. // Two arrays of the same type can be compared for equality. Additionally, a // pointer to an array allows the array elements to be modified // (array[index] = value). // // With channels, the # operator returns the number of elements buffered in the // channel. Two channels of the same type can be compared for equality (i.e. if // they were created with the same make call). Calling a channel value with // no arguments reads one element from the channel, returning the value and a // boolean indicating if the channel is closed. Calling a channel value with // one argument sends the argument to the channel. The channel's unary minus // operator closes the channel (_ = -channel). // // With maps, the # operator returns the number of elements in the map. Map // elements can be accessed using the index operator (map[key]) and also set // (map[key] = value). Calling a map value returns an iterator over the map that // can be used in a for loop. If a map's key type is string, map values take // priority over methods. // // With slices, the # operator returns the length of the slice. Slice elements // can be accessed using the index operator (slice[index]) and also set // (slice[index] = value). Calling a slice returns an iterator over its elements // that can be used in a for loop. Elements can be appended to a slice using the // add operator (new_slice = slice + element). // // With structs, fields can be accessed using the index operator // (struct[field]). As a special case, accessing field that is an array or // struct field will return a pointer to that value. Structs of the same type // can be tested for equality. Additionally, a pointer to a struct can have its // fields set (struct[field] = value). // // Struct field accessibility can be changed by setting the field's luar tag. // If the tag is empty (default), the field is accessed by its name and its // name with a lowercase first letter (e.g. "Field1" would be accessible using // "Field1" or "field1"). If the tag is "-", the field will not be accessible. // Any other tag value makes the field accessible through that name. // // Pointer values can be compared for equality. The pointed to value can be // changed using the pow operator (pointer = pointer ^ value). A pointer can be // dereferenced using the unary minus operator (value = -pointer). // // All other values (complex numbers, unsafepointer, uintptr) are converted to // *lua.LUserData with its Value field set to value and no custom metatable. // func New(L *lua.LState, value interface{}) lua.LValue { if value == nil { return lua.LNil } if lval, ok := value.(lua.LValue); ok { return lval } switch val := reflect.ValueOf(value); val.Kind() { case reflect.Bool: return lua.LBool(val.Bool()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return lua.LNumber(float64(val.Int())) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return lua.LNumber(float64(val.Uint())) case reflect.Float32, reflect.Float64: return lua.LNumber(val.Float()) case reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice: if val.IsNil() { return lua.LNil } fallthrough case reflect.Array, reflect.Struct: ud := L.NewUserData() ud.Value = val.Interface() ud.Metatable = getMetatable(L, val.Type()) return ud case reflect.Func: if val.IsNil() { return lua.LNil } return funcWrapper(L, val, false) case reflect.String: return lua.LString(val.String()) default: ud := L.NewUserData() ud.Value = val.Interface() return ud } } // NewType returns a new type generator for the given value's type. // // When the returned lua.LValue is called, a new value will be created that is // dependent on value's type: // // If value is a channel, the first argument optionally specifies the channel's // buffer size (defaults to 1). The new channel is returned. // // If value is a map, a new map is returned. // // If value is a slice, the first argument optionally specifies the slices's // length (defaults to 0), and the second argument optionally specifies the // slice's capacity (defaults to the first argument). The new slice is returned. // // All other types return a new pointer to the zero value of value's type. func NewType(L *lua.LState, value interface{}) lua.LValue { val := reflect.TypeOf(value) ud := L.NewUserData() ud.Value = val ud.Metatable = getTypeMetatable(L, val) return ud } type conversionError struct { Lua lua.LValue Hint reflect.Type } func (c conversionError) Error() string { if _, isNil := c.Lua.(*lua.LNilType); isNil { return fmt.Sprintf("cannot use nil as type %s", c.Hint) } var val interface{} if userData, ok := c.Lua.(*lua.LUserData); ok { val = userData.Value } else { val = c.Lua } return fmt.Sprintf("cannot use %v (type %T) as type %s", val, val, c.Hint) } type structFieldError struct { Field string Type reflect.Type } func (s structFieldError) Error() string { return `type ` + s.Type.String() + ` has no field ` + s.Field } func lValueToReflect(L *lua.LState, v lua.LValue, hint reflect.Type, tryConvertPtr *bool) (reflect.Value, error) { visited := make(map[*lua.LTable]reflect.Value) return lValueToReflectInner(L, v, hint, visited, tryConvertPtr) } func lValueToReflectInner(L *lua.LState, v lua.LValue, hint reflect.Type, visited map[*lua.LTable]reflect.Value, tryConvertPtr *bool) (reflect.Value, error) { if hint.Implements(refTypeLuaLValue) { return reflect.ValueOf(v), nil } isPtr := false switch converted := v.(type) { case lua.LBool: val := reflect.ValueOf(bool(converted)) if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } return val.Convert(hint), nil case lua.LChannel: val := reflect.ValueOf(converted) if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } return val.Convert(hint), nil case lua.LNumber: val := reflect.ValueOf(float64(converted)) if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } return val.Convert(hint), nil case *lua.LFunction: emptyIfaceHint := false switch { case hint == refTypeEmptyIface: emptyIfaceHint = true inOut := []reflect.Type{ reflect.SliceOf(refTypeEmptyIface), } hint = reflect.FuncOf(inOut, inOut, true) case hint.Kind() != reflect.Func: return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } fn := func(args []reflect.Value) []reflect.Value { thread, cancelFunc := L.NewThread() defer thread.Close() if cancelFunc != nil { defer cancelFunc() } thread.Push(converted) defer thread.SetTop(0) argCount := 0 for i, arg := range args { if i+1 == len(args) && hint.IsVariadic() { // arg is a varadic slice for j := 0; j < arg.Len(); j++ { arg := arg.Index(j) thread.Push(New(thread, arg.Interface())) argCount++ } break } thread.Push(New(thread, arg.Interface())) argCount++ } thread.Call(argCount, lua.MultRet) top := thread.GetTop() switch { case emptyIfaceHint: ret := reflect.MakeSlice(reflect.SliceOf(refTypeEmptyIface), top, top) for i := 1; i <= top; i++ { item, err := lValueToReflect(thread, thread.Get(i), refTypeEmptyIface, nil) if err != nil { panic(err) } ret.Index(i - 1).Set(item) } return []reflect.Value{ret} case top == hint.NumOut(): ret := make([]reflect.Value, top) var err error for i := 1; i <= top; i++ { outHint := hint.Out(i - 1) item := thread.Get(i) ret[i-1], err = lValueToReflect(thread, item, outHint, nil) if err != nil { panic(err) } } return ret } panic(fmt.Errorf("expecting %d return values, got %d", hint.NumOut(), top)) } return reflect.MakeFunc(hint, fn), nil case *lua.LNilType: switch hint.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer, reflect.Uintptr: return reflect.Zero(hint), nil } return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } case *lua.LState: val := reflect.ValueOf(converted) if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } return val.Convert(hint), nil case lua.LString: val := reflect.ValueOf(string(converted)) if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } return val.Convert(hint), nil case *lua.LTable: if existing := visited[converted]; existing.IsValid() { return existing, nil } if hint == refTypeEmptyIface { hint = reflect.MapOf(refTypeEmptyIface, refTypeEmptyIface) } switch { case hint.Kind() == reflect.Array: elemType := hint.Elem() length := converted.Len() if length != hint.Len() { return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } } s := reflect.New(hint).Elem() visited[converted] = s for i := 0; i < length; i++ { value := converted.RawGetInt(i + 1) elemValue, err := lValueToReflectInner(L, value, elemType, visited, nil) if err != nil { return reflect.Value{}, err } s.Index(i).Set(elemValue) } return s, nil case hint.Kind() == reflect.Slice: elemType := hint.Elem() length := converted.Len() s := reflect.MakeSlice(hint, length, length) visited[converted] = s for i := 0; i < length; i++ { value := converted.RawGetInt(i + 1) elemValue, err := lValueToReflectInner(L, value, elemType, visited, nil) if err != nil { return reflect.Value{}, err } s.Index(i).Set(elemValue) } return s, nil case hint.Kind() == reflect.Map: keyType := hint.Key() elemType := hint.Elem() s := reflect.MakeMap(hint) visited[converted] = s for key := lua.LNil; ; { var value lua.LValue key, value = converted.Next(key) if key == lua.LNil { break } lKey, err := lValueToReflectInner(L, key, keyType, visited, nil) if err != nil { return reflect.Value{}, err } lValue, err := lValueToReflectInner(L, value, elemType, visited, nil) if err != nil { return reflect.Value{}, err } s.SetMapIndex(lKey, lValue) } return s, nil case hint.Kind() == reflect.Ptr && hint.Elem().Kind() == reflect.Struct: hint = hint.Elem() isPtr = true fallthrough case hint.Kind() == reflect.Struct: s := reflect.New(hint) visited[converted] = s t := s.Elem() mt := &Metatable{ LTable: getMetatable(L, hint), } for key := lua.LNil; ; { var value lua.LValue key, value = converted.Next(key) if key == lua.LNil { break } if _, ok := key.(lua.LString); !ok { continue } fieldName := key.String() index := mt.fieldIndex(fieldName) if index == nil { return reflect.Value{}, structFieldError{ Type: hint, Field: fieldName, } } field := hint.FieldByIndex(index) lValue, err := lValueToReflectInner(L, value, field.Type, visited, nil) if err != nil { return reflect.Value{}, nil } t.FieldByIndex(field.Index).Set(lValue) } if isPtr { return s, nil } return t, nil } return reflect.Value{}, conversionError{ Lua: v, Hint: hint, } case *lua.LUserData: val := reflect.ValueOf(converted.Value) if tryConvertPtr != nil && val.Kind() != reflect.Ptr && hint.Kind() == reflect.Ptr && val.Type() == hint.Elem() { newVal := reflect.New(hint.Elem()) newVal.Elem().Set(val) val = newVal *tryConvertPtr = true } else { if !val.Type().ConvertibleTo(hint) { return reflect.Value{}, conversionError{ Lua: converted, Hint: hint, } } val = val.Convert(hint) if tryConvertPtr != nil { *tryConvertPtr = false } } return val, nil } panic("never reaches") } golang-layeh-gopher-luar-1.0.4/luar_test.go000066400000000000000000000140721331570700400206430ustar00rootroot00000000000000package luar import ( "reflect" "strings" "testing" "github.com/yuin/gopher-lua" ) func Test_luar_complex128(t *testing.T) { L := lua.NewState() defer L.Close() a := complex(float64(1), float64(2)) L.SetGlobal("a", New(L, a)) testReturn(t, L, `b = a`) b := L.GetGlobal("b").(*lua.LUserData).Value.(complex128) if a != b { t.Fatalf("expected a = b, got %v", b) } } type ChanAlias chan string func (ChanAlias) Test() string { return `I'm a "chan string" alias` } func (ChanAlias) hidden() { } type SliceAlias []string func (s SliceAlias) Len() int { return len(s) } func (s *SliceAlias) Append(v string) { *s = append(*s, v) } type MapAlias map[string]int func (m MapAlias) Y() int { return len(m) } func Test_type_methods(t *testing.T) { L := lua.NewState() defer L.Close() a := make(ChanAlias) var b SliceAlias = []string{"Hello", "world"} c := MapAlias{ "x": 15, } L.SetGlobal("a", New(L, a)) L.SetGlobal("b", New(L, &b)) L.SetGlobal("c", New(L, c)) testReturn(t, L, `return a:Test()`, `I'm a "chan string" alias`) testReturn(t, L, `len1 = b:Len(); b:Append("!")`) testReturn(t, L, `return len1, b:len()`, "2", "3") testReturn(t, L, `return c.x, c:y()`, "15", "1") } func Test_comparisons(t *testing.T) { L := lua.NewState() defer L.Close() { s := make([]int, 10) L.SetGlobal("s1", New(L, s)) L.SetGlobal("sp1", New(L, &s)) L.SetGlobal("s2", New(L, s)) L.SetGlobal("sp2", New(L, &s)) } { m := make(map[string]int, 10) L.SetGlobal("m1", New(L, m)) L.SetGlobal("mp1", New(L, &m)) L.SetGlobal("m2", New(L, m)) L.SetGlobal("mp2", New(L, &m)) } { c := make(chan string) L.SetGlobal("c1", New(L, c)) L.SetGlobal("cp1", New(L, &c)) L.SetGlobal("c2", New(L, c)) c3 := make(chan string) L.SetGlobal("c3", New(L, c3)) } { s := "" L.SetGlobal("sp1", New(L, &s)) L.SetGlobal("sp2", New(L, &s)) } testReturn(t, L, `return s1 == s1`, "true") testReturn(t, L, `return sp1 == sp2`, "true") testReturn(t, L, `return m1 == m1`, "true") testReturn(t, L, `return mp1 == mp2`, "true") testReturn(t, L, `return c1 == c1`, "true") testReturn(t, L, `return c1 == c3`, "false") testReturn(t, L, `return sp1 == sp2`, "true") } type TestSliceConversion struct { S []string } func Test_sliceconversion(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestSliceConversion{} L.SetGlobal("e", New(L, e)) testReturn(t, L, `e.S = {"a", "b", "", "c"}`) valid := true expecting := []string{"a", "b", "", "c"} if len(e.S) != len(expecting) { valid = false } else { for i, item := range e.S { if item != expecting[i] { valid = false break } } } if !valid { t.Fatalf("expecting %#v, got %#v", expecting, e.S) } } type TestMapConversion struct { S map[string]string } func Test_mapconversion(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestMapConversion{} L.SetGlobal("e", New(L, e)) testReturn(t, L, `e.S = {b = nil, c = "hello"}`) valid := true expecting := map[string]string{ "c": "hello", } if len(e.S) != len(expecting) { valid = false } else { for key, value := range e.S { expected, ok := expecting[key] if !ok || value != expected { valid = false break } } } if !valid { t.Fatalf("expecting %#v, got %#v", expecting, e.S) } if _, ok := e.S["b"]; ok { t.Fatal(`e.S["b"] should not be set`) } } func Test_udconversion(t *testing.T) { L := lua.NewState() defer L.Close() ud := L.NewUserData() ud.Value = "hello world" L.SetGlobal("ud", ud) var out int L.SetGlobal("out", New(L, &out)) testError(t, L, `_ = out ^ ud`, "cannot use hello world (type string) as type int") } func Test_arrayconversion(t *testing.T) { L := lua.NewState() defer L.Close() var arr [3]int L.SetGlobal("arr", New(L, &arr)) testReturn(t, L, `arr = arr ^ {10, 20, 11}; return arr[1], arr[2], arr[3]`, "10", "20", "11") } type TestInterfaceStruct struct{} func Test_interface(t *testing.T) { tbl := []struct { Code string Var func(L *lua.LState) lua.LValue Expected interface{} ExpectedType reflect.Type }{ { Code: `nil`, Expected: interface{}(nil), }, { Code: `"Hello"`, Expected: string("Hello"), }, { Code: `true`, Expected: bool(true), }, { Code: `1`, Expected: float64(1), }, { Code: `function(a, b) end`, ExpectedType: reflect.TypeOf(func(...interface{}) []interface{} { return nil }), }, { Code: `{hello = "world", [123] = 321}`, Expected: map[interface{}]interface{}{ string("hello"): string("world"), float64(123): float64(321), }, }, { Code: `var`, Var: func(L *lua.LState) lua.LValue { ud := L.NewUserData() ud.Value = "Hello World" return ud }, Expected: string("Hello World"), }, // TODO: LChannel // TODO: *LState } for _, cur := range tbl { func() { L := lua.NewState() defer L.Close() var out interface{} = TestInterfaceStruct{} L.SetGlobal("out", New(L, &out)) if cur.Var != nil { L.SetGlobal("var", cur.Var(L)) } if err := L.DoString(`_ = out ^ ` + cur.Code); err != nil { t.Fatal(err) } if cur.ExpectedType != nil { if reflect.TypeOf(out) != cur.ExpectedType { t.Fatalf("expected conversion of %#v = type %s, got type %s\n", cur.Code, cur.ExpectedType, reflect.TypeOf(out)) } } else if !reflect.DeepEqual(out, cur.Expected) { t.Fatalf("expected conversion of %#v = %#v (%T), got %#v (%T)\n", cur.Code, cur.Expected, cur.Expected, out, out) } }() } } func Test_recursivetable(t *testing.T) { L := lua.NewState() defer L.Close() var x interface{} L.SetGlobal("x", New(L, &x)) if err := L.DoString(`local tbl = {}; tbl.inner = tbl; _ = x ^ tbl`); err != nil { t.Fatal(err) } } func Test_tostringfallback(t *testing.T) { L := lua.NewState() defer L.Close() type Struct struct { } var out string L.SetGlobal("struct", New(L, &Struct{})) L.SetGlobal("out", New(L, &out)) if err := L.DoString(`_ = out ^ tostring(struct)`); err != nil { t.Fatal(err) } if !strings.HasPrefix(out, "userdata: ") { t.Fatalf("invalid tostring %#v\n", out) } } golang-layeh-gopher-luar-1.0.4/map.go000066400000000000000000000025641331570700400174210ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func mapIndex(L *lua.LState) int { ref, mt := check(L, 1) key := L.CheckAny(2) convertedKey, err := lValueToReflect(L, key, ref.Type().Key(), nil) if err == nil { item := ref.MapIndex(convertedKey) if item.IsValid() { L.Push(New(L, item.Interface())) return 1 } } if lstring, ok := key.(lua.LString); ok { if fn := mt.method(string(lstring)); fn != nil { L.Push(fn) return 1 } } return 0 } func mapNewIndex(L *lua.LState) int { ref, _ := check(L, 1) key := L.CheckAny(2) value := L.CheckAny(3) keyHint := ref.Type().Key() convertedKey, err := lValueToReflect(L, key, keyHint, nil) if err != nil { L.ArgError(2, err.Error()) } var convertedValue reflect.Value if value != lua.LNil { convertedValue, err = lValueToReflect(L, value, ref.Type().Elem(), nil) if err != nil { L.ArgError(3, err.Error()) } } ref.SetMapIndex(convertedKey, convertedValue) return 0 } func mapLen(L *lua.LState) int { ref, _ := check(L, 1) L.Push(lua.LNumber(ref.Len())) return 1 } func mapCall(L *lua.LState) int { ref, _ := check(L, 1) keys := ref.MapKeys() i := 0 fn := func(L *lua.LState) int { if i >= len(keys) { return 0 } L.Push(New(L, keys[i].Interface())) L.Push(New(L, ref.MapIndex(keys[i]).Interface())) i++ return 2 } L.Push(L.NewFunction(fn)) return 1 } golang-layeh-gopher-luar-1.0.4/map_test.go000066400000000000000000000033371331570700400204570ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_map(t *testing.T) { L := lua.NewState() defer L.Close() thangs := map[string]int{ "ABC": 123, "DEF": 456, } L.SetGlobal("thangs", New(L, thangs)) testReturn(t, L, `return thangs.ABC`, "123") testReturn(t, L, `return thangs.DEF`, "456") testReturn(t, L, `return thangs.GHI`, "nil") if err := L.DoString(`thangs.GHI = 789`); err != nil { t.Fatal(err) } testReturn(t, L, `thangs.ABC = nil`) if v := thangs["GHI"]; v != 789 { t.Fatalf(`expecting thangs["GHI"] = 789, got %d`, v) } if _, ok := thangs["ABC"]; ok { t.Fatal(`expecting thangs["ABC"] to be unset`) } } func Test_map_iterator(t *testing.T) { L := lua.NewState() defer L.Close() countries := map[string]string{ "JP": "Japan", "CA": "Canada", "FR": "France", } L.SetGlobal("countries", New(L, countries)) testReturn(t, L, `return #countries`, "3") const code = ` sorted = {} for k, v in countries() do table.insert(sorted, v) end table.sort(sorted)` if err := L.DoString(code); err != nil { t.Fatal(err) } testReturn(t, L, `return #sorted, sorted[1], sorted[2], sorted[3]`, "3", "Canada", "France", "Japan") } type TestMapUsers map[uint32]string func (m TestMapUsers) Find(name string) uint32 { for id, n := range m { if name == n { return id } } return 0 } func Test_map_methods(t *testing.T) { L := lua.NewState() defer L.Close() type User struct { Name string } users := TestMapUsers{ 1: "Tim", } L.SetGlobal("users", New(L, users)) testReturn(t, L, `return users[1]`, "Tim") testReturn(t, L, `return users[3]`, "nil") testReturn(t, L, `return users:Find("Tim")`, "1") testReturn(t, L, `return users:Find("Steve")`, "0") } golang-layeh-gopher-luar-1.0.4/metatable.go000066400000000000000000000017441331570700400206010ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) // Metatable is the Lua metatable for a Go type. type Metatable struct { *lua.LTable } // MT returns the metatable for value's type. nil is returned if value's type // does not use a custom metatable. func MT(L *lua.LState, value interface{}) *Metatable { if value == nil { return nil } switch typ := reflect.TypeOf(value); typ.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct: return &Metatable{ LTable: getMetatable(L, typ), } } return nil } func (m *Metatable) method(name string) lua.LValue { methods := m.RawGetString("methods").(*lua.LTable) if fn := methods.RawGetString(name); fn != lua.LNil { return fn } return nil } func (m *Metatable) fieldIndex(name string) []int { fields := m.RawGetString("fields").(*lua.LTable) if index := fields.RawGetString(name); index != lua.LNil { return index.(*lua.LUserData).Value.([]int) } return nil } golang-layeh-gopher-luar-1.0.4/metatable_test.go000066400000000000000000000012651331570700400216360ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_metatable(t *testing.T) { L := lua.NewState() defer L.Close() tbl := []struct { Value interface{} CustomMT bool }{ {"hello", false}, {123, false}, {1.23, false}, {nil, false}, {struct{}{}, true}, {&struct{}{}, true}, {[]string{}, true}, {make(chan string), true}, {(*string)(nil), true}, {func() {}, false}, {map[string]int{}, true}, } for _, v := range tbl { mt := MT(L, v.Value) if v.CustomMT && mt == nil { t.Fatalf("expected to have custom MT for %#v\n", v.Value) } else if !v.CustomMT && mt != nil { t.Fatalf("unexpected custom MT for %#v\n", v.Value) } } } golang-layeh-gopher-luar-1.0.4/ptr.go000066400000000000000000000025531331570700400174470ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func checkPtr(L *lua.LState, idx int) (ref reflect.Value, mt *Metatable) { ud := L.CheckUserData(idx) ref = reflect.ValueOf(ud.Value) if expecting := reflect.Ptr; ref.Kind() != expecting { L.ArgError(idx, "expecting "+expecting.String()) } mt = &Metatable{LTable: ud.Metatable.(*lua.LTable)} return } func ptrIndex(L *lua.LState) int { ref, mt := checkPtr(L, 1) key := L.CheckString(2) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } // fallback to non-pointer method ref = ref.Elem() mt = MT(L, ref.Interface()) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } return 0 } func ptrPow(L *lua.LState) int { ref, _ := checkPtr(L, 1) val := L.CheckAny(2) elem := ref.Elem() if !elem.CanSet() { L.RaiseError("unable to set pointer value") } value, err := lValueToReflect(L, val, elem.Type(), nil) if err != nil { L.ArgError(2, err.Error()) } elem.Set(value) L.SetTop(1) return 1 } func ptrUnm(L *lua.LState) int { ref, _ := checkPtr(L, 1) elem := ref.Elem() if !elem.CanInterface() { L.RaiseError("cannot interface pointer type " + elem.String()) } L.Push(New(L, elem.Interface())) return 1 } func ptrEq(L *lua.LState) int { ref1, _ := checkPtr(L, 1) ref2, _ := checkPtr(L, 2) L.Push(lua.LBool(ref1.Pointer() == ref2.Pointer())) return 1 } golang-layeh-gopher-luar-1.0.4/ptr_test.go000066400000000000000000000055651331570700400205140ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" "strings" ) func Test_ptr(t *testing.T) { L := lua.NewState() defer L.Close() str := "hello" L.SetGlobal("ptr", New(L, &str)) testReturn(t, L, `return -ptr`, "hello") } func Test_ptr_comparison(t *testing.T) { L := lua.NewState() defer L.Close() var ptr1 *string str := "hello" L.SetGlobal("ptr1", New(L, ptr1)) L.SetGlobal("ptr2", New(L, &str)) testReturn(t, L, `return ptr1 == nil`, "true") testReturn(t, L, `return ptr2 == nil`, "false") testReturn(t, L, `return ptr1 == ptr2`, "false") } func Test_ptr_assignment(t *testing.T) { L := lua.NewState() defer L.Close() str := "hello" L.SetGlobal("str", New(L, &str)) testReturn(t, L, `return tostring(-str)`, "hello") testReturn(t, L, `str = str ^ "world"; return (string.match(tostring(str), "userdata:"))`, "userdata:") testReturn(t, L, `return tostring(-str)`, "world") } type TestPtrNested struct { *TestPtrNestedChild } type TestPtrNestedChild struct { Value *string StructTestPerson } func Test_ptr_nested(t *testing.T) { L := lua.NewState() defer L.Close() a := TestPtrNested{ TestPtrNestedChild: &TestPtrNestedChild{ StructTestPerson: StructTestPerson{ Name: "Tim", }, }, } L.SetGlobal("a", New(L, &a)) L.SetGlobal("str_ptr", NewType(L, "")) testReturn(t, L, `return a.Value == nil`, "true") testReturn(t, L, `a.Value = str_ptr(); _ = a.Value ^ "hello"`) testReturn(t, L, `return a.Value == nil`, "false") testReturn(t, L, `return -a.Value`, "hello") testReturn(t, L, `return a.Name`, "Tim") } func Test_ptr_assignstruct(t *testing.T) { L := lua.NewState() defer L.Close() a := &StructTestPerson{ Name: "tim", } b := &StructTestPerson{ Name: "bob", } L.SetGlobal("a", New(L, a)) L.SetGlobal("b", New(L, b)) testReturn(t, L, `return a.Name`, "tim") testReturn(t, L, `_ = a ^ -b`) testReturn(t, L, `return a.Name`, "bob") } type TestStringType string func (s *TestStringType) ToUpper() { *s = TestStringType(strings.ToUpper(string(*s))) } func Test_ptr_nested2(t *testing.T) { L := lua.NewState() defer L.Close() a := [...]StructTestPerson{ {Name: "Tim"}, } s := []StructTestPerson{ {Name: "Tim", Age: 32}, } str := TestStringType("Hello World") L.SetGlobal("a", New(L, &a)) L.SetGlobal("s", New(L, s)) L.SetGlobal("p", New(L, &s[0])) L.SetGlobal("str", New(L, &str)) testReturn(t, L, `return a[1]:AddNumbers(1, 2, 3, 4, 5)`, "Tim counts: 15") testReturn(t, L, `return s[1]:AddNumbers(1, 2, 3, 4)`, "Tim counts: 10") testReturn(t, L, `return s[1].LastAddSum`, "10") testReturn(t, L, `return p:AddNumbers(1, 2, 3, 4, 5)`, "Tim counts: 15") testReturn(t, L, `return p.LastAddSum`, "15") testReturn(t, L, `return p.Age`, "32") testReturn(t, L, `p:IncreaseAge(); return p.Age`, "33") testReturn(t, L, `return -str`, "Hello World") testReturn(t, L, `str:ToUpper(); return -str`, "HELLO WORLD") } golang-layeh-gopher-luar-1.0.4/race_test.go000066400000000000000000000011521331570700400206050ustar00rootroot00000000000000// +build race package luar import ( "runtime" "testing" "github.com/yuin/gopher-lua" ) func Test_functhread(t *testing.T) { L := lua.NewState() defer L.Close() var fn func(x int) string L.SetGlobal("fn", New(L, &fn)) if err := L.DoString(`_ = fn ^ function(x) return tostring(x) .. "!" end`); err != nil { t.Fatal(err) } done := make(chan struct{}) defer close(done) go func() { for { select { case <-done: return default: } L.Push(lua.LNumber(1000)) runtime.Gosched() } }() if ret := fn(123); ret != "123!" { t.Fatalf("expected %#v, got %#v", "123!", ret) } } golang-layeh-gopher-luar-1.0.4/slice.go000066400000000000000000000032411331570700400177340ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func sliceIndex(L *lua.LState) int { ref, mt := check(L, 1) key := L.CheckAny(2) switch converted := key.(type) { case lua.LNumber: index := int(converted) if index < 1 || index > ref.Len() { L.ArgError(2, "index out of range") } val := ref.Index(index - 1) if (val.Kind() == reflect.Struct || val.Kind() == reflect.Array) && val.CanAddr() { val = val.Addr() } L.Push(New(L, val.Interface())) case lua.LString: if fn := mt.method(string(converted)); fn != nil { L.Push(fn) return 1 } return 0 default: L.ArgError(2, "must be a number or string") } return 1 } func sliceNewIndex(L *lua.LState) int { ref, _ := check(L, 1) index := L.CheckInt(2) value := L.CheckAny(3) if index < 1 || index > ref.Len() { L.ArgError(2, "index out of range") } val, err := lValueToReflect(L, value, ref.Type().Elem(), nil) if err != nil { L.ArgError(3, err.Error()) } ref.Index(index - 1).Set(val) return 0 } func sliceLen(L *lua.LState) int { ref, _ := check(L, 1) L.Push(lua.LNumber(ref.Len())) return 1 } func sliceCall(L *lua.LState) int { ref, _ := check(L, 1) i := 0 fn := func(L *lua.LState) int { if i >= ref.Len() { return 0 } item := ref.Index(i).Interface() L.Push(lua.LNumber(i + 1)) L.Push(New(L, item)) i++ return 2 } L.Push(L.NewFunction(fn)) return 1 } func sliceAdd(L *lua.LState) int { ref, _ := check(L, 1) item := L.CheckAny(2) hint := ref.Type().Elem() value, err := lValueToReflect(L, item, hint, nil) if err != nil { L.ArgError(2, err.Error()) } ref = reflect.Append(ref, value) L.Push(New(L, ref.Interface())) return 1 } golang-layeh-gopher-luar-1.0.4/slice_test.go000066400000000000000000000024041331570700400207730ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_slice(t *testing.T) { L := lua.NewState() defer L.Close() things := []string{ "cake", "wallet", "calendar", "phone", "speaker", } L.SetGlobal("things", New(L, things)) testReturn(t, L, `return #things, things[1], things[5]`, "5", "cake", "speaker") if err := L.DoString(`things[1] = "cookie"`); err != nil { t.Fatal(err) } if things[0] != "cookie" { t.Fatalf(`expected things[0] = "cookie", got %s`, things[0]) } } func Test_slice_2(t *testing.T) { L := lua.NewState() defer L.Close() items := make([]string, 0, 10) L.SetGlobal("items", New(L, items)) testReturn(t, L, `return #items`, "0") testReturn(t, L, `items = items + "hello" + "world"; return #items`, "2") testReturn(t, L, `return items[1]`, "hello") testReturn(t, L, `return items[2]`, "world") } func Test_slice_iterator(t *testing.T) { L := lua.NewState() defer L.Close() s := []string{ "hello", "there", } e := []string{} L.SetGlobal("s", New(L, s)) L.SetGlobal("e", New(L, e)) testReturn(t, L, `local itr = s(); local a, b = itr(); local c, d = itr(); return a, b, c, d`, "1", "hello", "2", "there") testReturn(t, L, `local itr = e(); local a, b = itr(); return a, b`, "nil", "nil") } golang-layeh-gopher-luar-1.0.4/struct.go000066400000000000000000000034711331570700400201660ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func structIndex(L *lua.LState) int { ref, mt := check(L, 1) key := L.CheckString(2) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } ref = reflect.Indirect(ref) index := mt.fieldIndex(key) if index == nil { return 0 } field := ref.FieldByIndex(index) if !field.CanInterface() { L.RaiseError("cannot interface field " + key) } if (field.Kind() == reflect.Struct || field.Kind() == reflect.Array) && field.CanAddr() { field = field.Addr() } L.Push(New(L, field.Interface())) return 1 } func structPtrIndex(L *lua.LState) int { ref, mt := check(L, 1) key := L.CheckString(2) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } ref = ref.Elem() mt = MT(L, ref.Interface()) if fn := mt.method(key); fn != nil { L.Push(fn) return 1 } index := mt.fieldIndex(key) if index == nil { return 0 } field := ref.FieldByIndex(index) if !field.CanInterface() { L.RaiseError("cannot interface field " + key) } if (field.Kind() == reflect.Struct || field.Kind() == reflect.Array) && field.CanAddr() { field = field.Addr() } L.Push(New(L, field.Interface())) return 1 } func structPtrNewIndex(L *lua.LState) int { ref, mt := check(L, 1) key := L.CheckString(2) value := L.CheckAny(3) ref = ref.Elem() mt = MT(L, ref.Interface()) index := mt.fieldIndex(key) if index == nil { L.RaiseError("unknown field " + key) } field := ref.FieldByIndex(index) if !field.CanSet() { L.RaiseError("cannot set field " + key) } val, err := lValueToReflect(L, value, field.Type(), nil) if err != nil { L.ArgError(2, err.Error()) } field.Set(val) return 0 } func structEq(L *lua.LState) int { ref1, _ := check(L, 1) ref2, _ := check(L, 2) L.Push(lua.LBool(ref1.Interface() == ref2.Interface())) return 1 } golang-layeh-gopher-luar-1.0.4/struct_test.go000066400000000000000000000124451331570700400212260ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_struct(t *testing.T) { L := lua.NewState() defer L.Close() tim := &StructTestPerson{ Name: "Tim", Age: 30, } john := StructTestPerson{ Name: "John", Age: 40, } L.SetGlobal("user1", New(L, tim)) L.SetGlobal("user2", New(L, john)) testReturn(t, L, `return user1.Name`, "Tim") testReturn(t, L, `return user1.Age`, "30") testReturn(t, L, `return user1:Hello()`, "Hello, Tim") testReturn(t, L, `return user2.Name`, "John") testReturn(t, L, `return user2.Age`, "40") testReturn(t, L, `local hello = user2.Hello; return hello(user2)`, "Hello, John") } func Test_struct_tostring(t *testing.T) { L := lua.NewState() defer L.Close() p1 := StructTestPerson{ Name: "Tim", Age: 99, } p2 := StructTestPerson{ Name: "John", Age: 2, } L.SetGlobal("p1", New(L, &p1)) L.SetGlobal("p2", New(L, &p2)) testReturn(t, L, `return tostring(p1)`, `Tim (99)`) testReturn(t, L, `return tostring(p2)`, `John (2)`) } func Test_struct_pointers(t *testing.T) { L := lua.NewState() defer L.Close() p1 := StructTestPerson{ Name: "Tim", } p2 := StructTestPerson{ Name: "John", } L.SetGlobal("p1", New(L, &p1)) L.SetGlobal("p1_alias", New(L, &p1)) L.SetGlobal("p2", New(L, &p2)) testReturn(t, L, `return -p1 == -p1`, "true") testReturn(t, L, `return -p1 == -p1_alias`, "true") testReturn(t, L, `return p1 == p1`, "true") testReturn(t, L, `return p1 == p1_alias`, "true") testReturn(t, L, `return p1 == p2`, "false") } func Test_struct_lstate(t *testing.T) { L := lua.NewState() defer L.Close() p := StructTestPerson{ Name: "Tim", } L.SetGlobal("p", New(L, &p)) testReturn(t, L, `return p:AddNumbers(1, 2, 3, 4, 5)`, "Tim counts: 15") } type StructTestHidden struct { Name string `luar:"name"` Name2 string `luar:"Name"` Str string Hidden bool `luar:"-"` } func Test_struct_hiddenfields(t *testing.T) { L := lua.NewState() defer L.Close() a := &StructTestHidden{ Name: "tim", Name2: "bob", Str: "asd123", Hidden: true, } L.SetGlobal("a", New(L, a)) testReturn(t, L, `return a.name`, "tim") testReturn(t, L, `return a.Name`, "bob") testReturn(t, L, `return a.str`, "asd123") testReturn(t, L, `return a.Str`, "asd123") testReturn(t, L, `return a.Hidden`, "nil") testReturn(t, L, `return a.hidden`, "nil") } func Test_struct_method(t *testing.T) { L := lua.NewState() defer L.Close() p := StructTestPerson{ Name: "Tim", Age: 66, } L.SetGlobal("p", New(L, &p)) testReturn(t, L, `return p:hello()`, "Hello, Tim") testReturn(t, L, `return p.age`, "66") } type NestedPointer struct { B NestedPointerChild } type NestedPointerChild struct { } func (*NestedPointerChild) Test() string { return "Pointer test" } func Test_struct_nestedptrmethod(t *testing.T) { L := lua.NewState() defer L.Close() a := NestedPointer{} L.SetGlobal("a", New(L, &a)) testReturn(t, L, `return a.b:Test()`, "Pointer test") } type TestStructEmbeddedType struct { TestStructEmbeddedTypeString } type TestStructEmbeddedTypeString string func Test_struct_embeddedtype(t *testing.T) { L := lua.NewState() defer L.Close() a := TestStructEmbeddedType{ TestStructEmbeddedTypeString: "hello", } L.SetGlobal("a", New(L, &a)) testReturn(t, L, `a.TestStructEmbeddedTypeString = "world"`) if val := a.TestStructEmbeddedTypeString; val != "world" { t.Fatalf("expecting %s, got %s", "world", val) } } type TestStructEmbedded struct { StructTestPerson P StructTestPerson P2 StructTestPerson `luar:"other"` } func Test_struct_embedded(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestStructEmbedded{} L.SetGlobal("e", New(L, e)) testReturn( t, L, ` e.StructTestPerson = { Name = "Bill", Age = 33 } e.P = { Name = "Tim", Age = 94, Friend = { Name = "Bob", Age = 77 } } e.other = { Name = "Dale", Age = 26 } `, ) { expected := StructTestPerson{ Name: "Bill", Age: 33, } if e.StructTestPerson != expected { t.Fatalf("expected %#v, got %#v", expected, e.StructTestPerson) } } { expected := StructTestPerson{ Name: "Bob", Age: 77, } if *(e.P.Friend) != expected { t.Fatalf("expected %#v, got %#v", expected, *e.P.Friend) } } { expected := StructTestPerson{ Name: "Dale", Age: 26, } if e.P2 != expected { t.Fatalf("expected %#v, got %#v", expected, e.P2) } } } type TestPointerReplaceHidden struct { A string `luar:"q"` B int `luar:"other"` C int `luar:"-"` } func Test_struct_pointerreplacehidden(t *testing.T) { L := lua.NewState() defer L.Close() e := &TestPointerReplaceHidden{} L.SetGlobal("e", New(L, e)) testReturn( t, L, ` _ = e ^ { q = "Cat", other = 675 } `, ) expected := TestPointerReplaceHidden{ A: "Cat", B: 675, } if *e != expected { t.Fatalf("expected %v, got %v", expected, *e) } testError( t, L, ` _ = e ^ { C = 333 } `, `type luar.TestPointerReplaceHidden has no field C`, ) } func Test_struct_ptreq(t *testing.T) { L := lua.NewState() defer L.Close() p1 := StructTestPerson{ Name: "Tim", } p2 := StructTestPerson{ Name: "Tim", } L.SetGlobal("p1", New(L, &p1)) L.SetGlobal("p2", New(L, &p2)) if &p1 == &p2 { t.Fatal("expected structs to be unequal") } testReturn(t, L, `return p1 == p2`, "false") } golang-layeh-gopher-luar-1.0.4/type.go000066400000000000000000000021451331570700400176200ustar00rootroot00000000000000package luar import ( "reflect" "github.com/yuin/gopher-lua" ) func checkType(L *lua.LState, idx int) reflect.Type { ud := L.CheckUserData(idx) return ud.Value.(reflect.Type) } func typeCall(L *lua.LState) int { ref := checkType(L, 1) var value reflect.Value switch ref.Kind() { case reflect.Chan: buffer := L.OptInt(2, 0) if buffer < 0 { L.ArgError(2, "negative buffer size") } if ref.ChanDir() != reflect.BothDir { L.RaiseError("unidirectional channel type") } value = reflect.MakeChan(ref, buffer) case reflect.Map: value = reflect.MakeMap(ref) case reflect.Slice: length := L.OptInt(2, 0) capacity := L.OptInt(3, length) if length < 0 { L.ArgError(2, "negative length") } if capacity < 0 { L.ArgError(3, "negative capacity") } if length > capacity { L.RaiseError("length > capacity") } value = reflect.MakeSlice(ref, length, capacity) default: value = reflect.New(ref) } L.Push(New(L, value.Interface())) return 1 } func typeEq(L *lua.LState) int { type1 := checkType(L, 1) type2 := checkType(L, 2) L.Push(lua.LBool(type1 == type2)) return 1 } golang-layeh-gopher-luar-1.0.4/type_test.go000066400000000000000000000020501331570700400206520ustar00rootroot00000000000000package luar import ( "testing" "github.com/yuin/gopher-lua" ) func Test_type_slice(t *testing.T) { L := lua.NewState() defer L.Close() type ints []int L.SetGlobal("newInts", NewType(L, ints{})) testReturn(t, L, `ints = newInts(1); return #ints`, "1") testReturn(t, L, `ints = newInts(0, 10); return #ints`, "0") } func Test_type(t *testing.T) { L := lua.NewState() defer L.Close() tim := &StructTestPerson{ Name: "Tim", } L.SetGlobal("user1", New(L, tim)) L.SetGlobal("Person", NewType(L, StructTestPerson{})) L.SetGlobal("People", NewType(L, map[string]*StructTestPerson{})) testReturn(t, L, `user2 = Person(); user2.Name = "John"; user2.Friend = user1`) testReturn(t, L, `return user2.Name`, "John") testReturn(t, L, `return user2.Friend.Name`, "Tim") testReturn(t, L, `everyone = People(); everyone["tim"] = user1; everyone["john"] = user2`) everyone := L.GetGlobal("everyone").(*lua.LUserData).Value.(map[string]*StructTestPerson) if len(everyone) != 2 { t.Fatalf("expecting len(everyone) = 2, got %d", len(everyone)) } } golang-layeh-gopher-luar-1.0.4/util.go000066400000000000000000000012521331570700400176120ustar00rootroot00000000000000package luar import ( "fmt" "reflect" "unicode" "unicode/utf8" "github.com/yuin/gopher-lua" ) func check(L *lua.LState, idx int) (ref reflect.Value, mt *Metatable) { ud := L.CheckUserData(idx) ref = reflect.ValueOf(ud.Value) mt = &Metatable{LTable: ud.Metatable.(*lua.LTable)} return } func tostring(L *lua.LState) int { ud := L.CheckUserData(1) if stringer, ok := ud.Value.(fmt.Stringer); ok { L.Push(lua.LString(stringer.String())) } else { L.Push(lua.LString(ud.String())) } return 1 } func getUnexportedName(name string) string { first, n := utf8.DecodeRuneInString(name) if n == 0 { return name } return string(unicode.ToLower(first)) + name[n:] }