From 467210daee147508f1abfed52dcb82c28dd27f3f Mon Sep 17 00:00:00 2001 From: Sebastian Waschik Date: Thu, 14 Dec 2023 11:49:50 +0100 Subject: [PATCH] Return a closure without arguments in gfind --- _glua-tests/issues.lua | 15 +++++++++++++++ stringlib.go | 10 +++++----- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/_glua-tests/issues.lua b/_glua-tests/issues.lua index 6d6343ab..460cf916 100644 --- a/_glua-tests/issues.lua +++ b/_glua-tests/issues.lua @@ -490,3 +490,18 @@ function test() assert(b == nil) end test() + +-- issue #462 +function test() + local x = string.gmatch("asdf", "a") + assert(x() == "a", "check gmatch callback") + + local expected = { + "a", + "c", + } + for i in string.gmatch("abc", "[ac]") do + assert(i == table.remove(expected, 1), "check gmatch inside loop") + end +end +test() diff --git a/stringlib.go b/stringlib.go index f484c2b3..8ab8dc15 100644 --- a/stringlib.go +++ b/stringlib.go @@ -14,7 +14,7 @@ func OpenString(L *LState) int { //_, ok := L.G.builtinMts[int(LTString)] //if !ok { mod = L.RegisterModule(StringLibName, strFuncs).(*LTable) - gmatch := L.NewClosure(strGmatch, L.NewFunction(strGmatchIter)) + gmatch := L.NewFunction(strGmatch) mod.RawSetString("gmatch", gmatch) mod.RawSetString("gfind", gmatch) mod.RawSetString("__index", mod) @@ -299,7 +299,7 @@ type strMatchData struct { } func strGmatchIter(L *LState) int { - md := L.CheckUserData(1).Value.(*strMatchData) + md := L.CheckUserData(UpvalueIndex(1)).Value.(*strMatchData) str := md.str matches := md.matches idx := md.pos @@ -331,11 +331,11 @@ func strGmatch(L *LState) int { if err != nil { L.RaiseError(err.Error()) } - L.Push(L.Get(UpvalueIndex(1))) ud := L.NewUserData() ud.Value = &strMatchData{str, 0, mds} - L.Push(ud) - return 2 + f := L.NewClosure(strGmatchIter, ud) + L.Push(f) + return 1 } func strLen(L *LState) int {