Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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}

5 comments

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.

0

I'm confused by this question.

0

Ohh so basically you have to initialize it at the start. Welp thanks I thought i would be able to but owell

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

0

Lua or lua if you're lazy, but never LUA.

1 answer

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.

1 comment

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.