Skip to content

Commit f048c34

Browse files
committed
filter: lua: fieldName and fieldByName
1 parent 2c8e963 commit f048c34

File tree

3 files changed

+35
-9
lines changed

3 files changed

+35
-9
lines changed

filter/lua.go

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,21 @@ func registerLUATypes(l *lua.LState, comp baker.ComponentParams) {
8787
return 2
8888
}))
8989

90-
// Create the fields table.
90+
l.SetGlobal("fieldByName", l.NewFunction(func(L *lua.LState) int {
91+
fname := L.CheckString(1)
92+
fidx, ok := comp.FieldByName(fname)
93+
if !ok {
94+
l.Push(lua.LNil)
95+
} else {
96+
l.Push(lua.LNumber(fidx))
97+
}
98+
return 1
99+
}))
100+
101+
// Create the fieldNaames table.
91102
fields := l.NewTable()
92-
for i, n := range comp.FieldNames {
93-
fields.RawSetString(n, lua.LNumber(i))
103+
for fidx, fname := range comp.FieldNames {
104+
fields.RawSet(lua.LNumber(fidx), lua.LString(fname))
94105
}
95106
l.SetGlobal("fieldNames", fields)
96107
}

filter/lua_test.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,19 +87,26 @@ func TestLUAFilter(t *testing.T) {
8787
want [][3]string // contains non discarded records with, for each of them, the 3 fields we want
8888
}{
8989
{
90-
name: "swapFieldsWithIndex",
90+
name: "swapFields",
9191
record: "abc,def,ghi",
9292
want: [][3]string{
9393
{"abc", "ghi", "def"},
9494
},
9595
},
9696
{
97-
name: "swapFieldsWithNames",
97+
name: "_fieldByName",
9898
record: "abc,def,ghi",
9999
want: [][3]string{
100100
{"abc", "ghi", "def"},
101101
},
102102
},
103+
{
104+
name: "_fieldNames",
105+
record: "abc,def,ghi",
106+
want: [][3]string{
107+
{"foo", "bar", "baz"},
108+
},
109+
},
103110
{
104111
name: "_createRecord",
105112
record: "abc,def,ghi",

filter/testdata/lua_test.lua

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,27 @@
1-
function swapFieldsWithIndex(rec, next)
1+
function swapFields(rec, next)
22
local f1, f2
33
f1 = rec:get(1)
44
rec:set(1, rec:get(2))
55
rec:set(2, f1)
66
next(rec)
77
end
88

9-
function swapFieldsWithNames(rec, next)
9+
function _fieldByName(rec, next)
1010
local f1, f2
11-
f1 = rec:get(fieldNames["bar"])
12-
rec:set(1, rec:get(fieldNames["baz"]))
11+
f1 = rec:get(fieldByName("bar"))
12+
rec:set(1, rec:get(fieldByName("baz")))
1313
rec:set(2, f1)
1414
next(rec)
1515
end
1616

17+
function _fieldNames(rec, next)
18+
-- set each field to its name
19+
rec:set(0, fieldNames[0])
20+
rec:set(1, fieldNames[1])
21+
rec:set(2, fieldNames[2])
22+
next(rec)
23+
end
24+
1725
function _createRecord(rec, next)
1826
newrec = createRecord()
1927
newrec:set(0, "hey")

0 commit comments

Comments
 (0)