5 ms·
> if you use LuaJIT you can use zero based indices and a powerful FFI Not entirely, Lua standard libraries still expect everything to be one-indexed, while FFI
by pierrec 5y ago
> if you use LuaJIT you can use zero based indices and a powerful FFI
Not entirely, Lua standard libraries still expect everything to be one-indexed, while FFI structures are zero indexed. So with LuaJIT you often end up with a mix of 0 and 1 indexed code, which in my experience was workable but definitely a pain point.
- Rochus 5y agoYou should avoid the Lua C API in LuaJIT because it is not supported by the JIT (i.e. it makes your code running in the interpreter instead of the JIT). Using zero based indices in Lua code running on LuaJIT works well.
- pierrec 5y agoI'm not talking about the Lua C API, but things as simple as this: > stuff = {"one", "two", "three"} > stuff[1] one These native Lua structures are baked in, and they're a lot more flexible than FFI structures - presumably if you're using Lua, it's because you want to take advantage of that flexibility and those affordances. FWIW I've written a lot of LuaJIT, and usually I kept the lower-level FFI stuff separate from the higher-level code using Lua data structures, so I rarely encountered that discrepancy between them, but still something to keep in mind.
- Rochus 5y agoYou can e.g. do > stuff = { [0]="one", [1]="two" } > print(stuff[0]) one Works well; I wrote e.g. https://github.com/rochus-keller/Smalltalk#a-smalltalk-80-interpreted-virtual-machine-on-luajit https://github.com/rochus-keller/Smalltalk#a-smalltalk-80-in... that way. EDIT: even this works > stuff = { [0]="one", "two", "three" } > print(stuff[0]) -> one > print(stuff[1]) -> two
- pansa2 5y ago> stuff = { [0]="one", "two", "three" } In this case, is it possible to make iteration start with the element at index 0? Maybe by implementing a custom version of `ipairs`?
- Rochus 5y agoWhen using > stuff = { [0]="one", "two", "three" } > for k,v in pairs(stuff) do print(v) end it prints all three elements in the correct order. I rarely use iterators for performance reasons anyway. Instead of ipairs one can use > for i=0,#stuff do print(stuff[i]) end