Generics in Lua
Lua doesn’t have built-in support for generics, but we can simulate some generic-like behavior using tables and functions. Here’s an example that demonstrates concepts similar to the original code:
-- As an example of a function that works with different types,
-- tableIndex takes a table and a value, and returns the index
-- of the first occurrence of v in t, or -1 if not present.
function tableIndex(t, v)
for i, value in ipairs(t) do
if value == v then
return i
end
end
return -1
end
-- As an example of a "generic" type, List is a
-- singly-linked list that can hold values of any type.
List = {}
List.__index = List
function List.new()
return setmetatable({head = nil, tail = nil}, List)
end
function List:push(v)
local newElement = {value = v, next = nil}
if self.tail == nil then
self.head = newElement
self.tail = newElement
else
self.tail.next = newElement
self.tail = newElement
end
end
-- AllElements returns all the List elements as a table.
function List:allElements()
local elements = {}
local current = self.head
while current do
table.insert(elements, current.value)
current = current.next
end
return elements
end
-- Main function to demonstrate usage
function main()
local s = {"foo", "bar", "zoo"}
-- When using tableIndex, we don't need to specify types
-- as Lua is dynamically typed.
print("index of zoo:", tableIndex(s, "zoo"))
local lst = List.new()
lst:push(10)
lst:push(13)
lst:push(23)
print("list:", table.concat(lst:allElements(), " "))
end
main()
To run the program, save it as generics_example.lua
and use the Lua interpreter:
$ lua generics_example.lua
index of zoo: 3
list: 10 13 23
This Lua code demonstrates concepts similar to generics in the original example:
The
tableIndex
function works with tables of any type, similar to the genericSlicesIndex
function in the original.The
List
type can hold elements of any type, simulating a generic data structure.Methods like
push
andallElements
work with any type of data stored in the list.The main function demonstrates using these “generic-like” constructs with both strings and numbers.
While Lua doesn’t have explicit generic syntax, its dynamic typing and flexible table structure allow for creating code that works with multiple types in a similar way to generics in statically-typed languages.