Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is this the correct way to initialize an array in LUA?

Asked by 7 years ago

So I know in C you can initialize an array by saying int arr[4]; which means an array of 4 elements but in lua is it the same case? so for example

local arr[4]
v=game.Players:children()
for i=1, #v do
    arr[i] = 1+i
end

So in this case would it output arr[1] = 2, arr[2] = 3, arr[3] = 4, arr[4] = 5

Also can i put all the elements to one value like 0 in an array in LUA like this? arr[5] = {0}

0
No, b/c "arr" requires to be a table to accomplish that; essentially you're telling the computer "set variable position # to # + 1," and not "set table position # to # + 1." The first would result in an error. TheeDeathCaster 2368 — 7y
0
I'm confused by this question. OldPalHappy 1477 — 7y
0
Ohh so basically you have to initialize it at the start. Welp thanks I thought i would be able to but owell windstrike 27 — 7y
0
Learn the basics of BNF notation and consult the official Lua manual. Much faster than asking questions and gives you a fuller understanding of the language: https://www.lua.org/manual/5.1/manual.html#2.5.7 duckwit 1404 — 7y
0
Lua or lua if you're lazy, but never LUA. Kampfkarren 215 — 7y

1 answer

Log in to vote
1
Answered by 7 years ago

No, you can't.

Lua is designed to be a very lightweight language. This is why it omits a lot of quality of life features from other languages, like increments and the continue operator. This makes the instructions a VM needs to know very slim, giving it a huge performance boost.

One of the features it omits is declaring arrays (called tables in Lua) by a fixed length.

All tables are dynamic, and declared like so:

local t = {}

You can proceed to fill in your data in between the curly braces.

0
Furthermore, the closest thing you can do to initialize an array-like table's elements to zero is to use a for loop to assign each element's value to zero one by one. Otherwise you can use a metatable with an '__index' metafield set to 'function() return 0 end' so that it returns zero when attempting to get an element that does not yet exist in the table. Link150 1355 — 7y
Ad

Answer this question