Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions table.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,27 +324,44 @@ func (tb *LTable) RawGetString(key string) LValue {

// ForEach iterates over this table of elements, yielding each in turn to a given function.
func (tb *LTable) ForEach(cb func(LValue, LValue)) {
tb.ForEachWithError(func(key, value LValue) error {
cb(key, value)
return nil
})
}

// ForEachWithError iterates over this table of elements, yielding each in turn
// to a given function. If it receives a non-nil error from its callback, it
// breaks and passes it back to its caller.
func (tb *LTable) ForEachWithError(cb func(LValue, LValue) error) error {
if tb.array != nil {
for i, v := range tb.array {
if v != LNil {
cb(LNumber(i+1), v)
if err := cb(LNumber(i+1), v); err != nil {
return err
}
}
}
}
if tb.strdict != nil {
for k, v := range tb.strdict {
if v != LNil {
cb(LString(k), v)
if err := cb(LString(k), v); err != nil {
return err
}
}
}
}
if tb.dict != nil {
for k, v := range tb.dict {
if v != LNil {
cb(k, v)
if err := cb(k, v); err != nil {
return err
}
}
}
}
return nil
}

// This function is equivalent to lua_next ( http://www.lua.org/manual/5.1/manual.html#lua_next ).
Expand Down
27 changes: 27 additions & 0 deletions table_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lua

import (
"fmt"
"testing"
)

Expand Down Expand Up @@ -231,3 +232,29 @@ func TestTableForEach(t *testing.T) {
}
})
}

func TestTableForEachWithError(t *testing.T) {
tbl := newLTable(0, 0)
tbl.Append(LNumber(1))
tbl.Append(LNumber(2))
tbl.Append(LNumber(3))
tbl.Append(LNil)
tbl.Append(LNumber(5))

tbl.RawSetH(LString("a"), LString("a"))
tbl.RawSetH(LString("b"), LString("b"))
tbl.RawSetH(LString("c"), LString("c"))

tbl.RawSetH(LTrue, LString("true"))
tbl.RawSetH(LFalse, LString("false"))

testError := fmt.Errorf("test error")
runCount := 0
err := tbl.ForEachWithError(func(key, value LValue) error {
runCount += 1
return testError
})

errorIfNotEqual(t, testError, err)
errorIfNotEqual(t, 1, runCount)
}