How to pass and iterate a list of objects from C# to NLua

1.1k Views Asked by At

how should I pass and iterate a list of objects from C# to Lua?

My example with an array of int, when I use custom classes I get the same result:

state_ = new Lua();
state_.LoadCLRPackage();

var candidates = new int[] { 0, 1, 2, 3, 4, 5 };

state_["Candidates"] = candidates;

state_.DoString(script);

var b = state_["Candidates"] as int[];

return toRetrun;

Where the script is

-- Iterate each candidate
for k,v in ipairs(Candidates) do

    print(k, Candidates[k])

end

The output is:

1   1
2   2
3   3
4   4
5   5

It skips the first one and I get the exception: "Index was outside the bounds of the array." What's wrong with my code?

2

There are 2 best solutions below

0
Michele mpp Marostica On BEST ANSWER

C# Lists have the Count property. It can be used as upper-bound for iterations:

[...]
var candidates = new List<int> { 0, 1, 2, 3, 4, 5 };
[...]

[...]
-- Iterate each candidate
for candidateCount = 0, Candidates.Count - 1 do
[...]
3
Roman Marusyk On

In Lua, indexing generally starts at index 1. From docs

it is customary in Lua to start arrays with index 1

Try something like this:

for i = 0, #Candidates do
     print(i, Candidates[i])
end

as I konw ipairs() only supports 1 indexing, so you'll have to define your own function or just use a regular for instead.

I'm not sure but also try

for k,v in ipairs(Candidates), Candidates, -1 do
  print(k, Candidates[k])
end