Array values
are very common argument types, and are often returned by
functions. LuaInterface provides a convenient index notation for
accessing the values, but note that the index runs from zero
to Length-1
!
Creating an array of strings is easy. Use the type name followed by the size in square brackets - this is consistent with the C# syntax.
ss = String[3]
ss[0] = "one"
ss[1] = "two"
ss[2] = "three"
However, note
that you can only initialize values in this simple way if you are
dealing with objects and not numbers. Then you have to use
Array.SetValue
explicitly.
d = Double[4]
d[0] = 1.0
Will result in a: System.InvalidCastException: Unable to cast object of type
'System.Double[]' to type 'System.Object[]'.
You will need to do:
d:SetValue(0,1.0)
There are no implicit conversions of Lua tables into .NET types, but it is easy to do manually. Here is a useful function for creating an array of doubles from a table:
function make_double_array (tbl)
local arr = Double[#tbl]
for i,v in ipairs(tbl) do
arr:SetValue(v,i-1)
end
return arr
end
Other collection types are treated similarly; generally, if the object is indexable, Lua will be able to index it naturally as well.
There is no
direct support in Lua for enumerables, as there is in C# with
the foreach
statement, but
it is not difficult to write a function that will allow us to
iterate through any such collection using a Lua
for
statement:
function enum(o)
local e = o:GetEnumerator()
return function()
if e:MoveNext() then
return e.Current
end
end
end
for v in enum(args) do print(v) end