-
Notifications
You must be signed in to change notification settings - Fork 1
Preallocation
Gilberto Romero edited this page Feb 15, 2016
·
5 revisions
t = @[number]
t = @[number][number][...]
t = @:<expression>:[number]
t = @:<expression>:[number][number][...]In Luva, preallocation is used to make space in the array-part of a table. It can be very handy at times, but it's mostly used for speed gains.
// This will preallocate the array part of the table 'a' from 1 to 100:
local a = @[100]
// Similarly, we can also preallocate multidimensional arrays.
// This creates a 16x16 array.
local a2 = @[16][16]
// There's no limit to the number of dimensions, of course:
local a3 = @[4][4][4][4]
// Nor is there any limit to the size of the array (except for available hardware memory):
local a4 = @[1024]
/*
It should be noted, however, that you must use a number when preallocating an array.
This will not work:
local x = 10
local a5 = @[x]
So, the catch is you must always use a number.
Keep in mind that it will be rounded down if it's a decimal.
Hex and binary numbers also work, as they're automatically turned into numbers during tokenization.
*/
// Though, the array doesn't have to be filled with nil. We can specify what value to fill it with.
// This will create a 2x2 array, filled with the number 10.
local a6 = @:10:[2][2]
// Anything put in :: is evaluated as an expression, so if we really wanted to, we could do this:
local a7 = @:@:true:[8]:[4][4]
// This is a 4x4 array with each array containing an array with 8 true values in it.
// Of course, we can also do things like this:
local a8 = @:(2 + 4) * 6:[4][4]
// Due to limitations of my compiler, however, this would be inefficient to do.
// The much faster optimization that could be made here is this:
local temp = (2 + 4) * 6
local a9 = @:temp:[4][4]
// Preallocating arrays in general should be taken advantage of.
// For example, the following code:
local a = []
for i = 1, 10 {
a[i] = i
}
// Will be more than 3x slower than:
local a = @[10]
for i = 1, 10 {
a[i] = i
}