diff --git a/common/space_lua/stdlib/table.ts b/common/space_lua/stdlib/table.ts index 022846ac..5e1a2a6e 100644 --- a/common/space_lua/stdlib/table.ts +++ b/common/space_lua/stdlib/table.ts @@ -160,7 +160,7 @@ export const tableApi = new LuaTable({ * @param tbl - The table to search. * @param criteriaFn - The criteria function. * @param fromIndex - The index to start searching from. - * @returns The first matching element, or nil if no element is found. + * @returns Lua multi value of index, value, or nil if no element is found. */ find: new LuaBuiltinFunction( async ( @@ -173,7 +173,7 @@ export const tableApi = new LuaTable({ for (let i = startIndex; i <= tbl.length; i++) { const val = await luaGet(tbl, i, sf); if (await criteriaFn.call(sf, val)) { - return val; + return new LuaMultiRes([i, val]); } } return null; diff --git a/common/space_lua/stdlib/table_test.lua b/common/space_lua/stdlib/table_test.lua index 8d73f10a..a7d55eda 100644 --- a/common/space_lua/stdlib/table_test.lua +++ b/common/space_lua/stdlib/table_test.lua @@ -141,3 +141,10 @@ assertEqual(packed[1], 1) assertEqual(packed[2], 2) assertEqual(packed[3], 3) assertEqual(packed.n, 3) + +-- Test table.find +local t = { 0, 1, 2, 3 } +local idx, two = table.find(t, function(v) return v == 2 end) +assertEqual(idx, 3) +assertEqual(two, 2) +assertEqual(table.find(t, function(v) return v == 4 end), nil) \ No newline at end of file diff --git a/website/API/table.md b/website/API/table.md index 28a911e3..7e0710f7 100644 --- a/website/API/table.md +++ b/website/API/table.md @@ -97,16 +97,16 @@ print(x, y) -- prints: banana orange # Non-standard functions ## table.find(table, criteriaFn, fromIndex?) -Finds an element in a table that matches a criteria function. Returns the first matching element or nil if no element is found. +Finds an element in a table that matches a criteria function. Returns a Lua multi value of index and first element or nil if no element is found. Example: ```lua local numbers = {1, 2, 3, 4, 5} -local firstEven = table.find(numbers, function(n) return n % 2 == 0 end) +local _, firstEven = table.find(numbers, function(n) return n % 2 == 0 end) print(firstEven) -- prints: 2 -- With fromIndex parameter -local firstEvenAfter3 = table.find(numbers, function(n) return n % 2 == 0 end, 3) +local _, firstEvenAfter3 = table.find(numbers, function(n) return n % 2 == 0 end, 3) print(firstEvenAfter3) -- prints: 4 -- No match case