2

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?

Michele mpp Marostica
  • 2,445
  • 4
  • 29
  • 45

2 Answers2

1

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
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    Thanks for the suggestion but the # operator woks only on tables. The solution is easy tho, I forgot that C# Lists have the Count property and I can use it in Lua. So your answer is correct if you put Candidates.Count instead of #Candidates and I use a List instead of an Array in C# – Michele mpp Marostica May 21 '19 at 21:05
  • Glad to have been of help. Also please see an update – Roman Marusyk May 21 '19 at 21:08
  • I tested the code in the update. It starts correctly from the first element but I still get an index out of bound exception at the end of the list – Michele mpp Marostica May 21 '19 at 21:12
1

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
[...]
Michele mpp Marostica
  • 2,445
  • 4
  • 29
  • 45