I have six variables, that these variables have different position on the screen, I wanna put different images in these variables, hence i have an Array with the images.
misImagenes = {[1] = "rec/ro.png",[2] ="rec/az.png",[3] ="rec/ros.png",[4] ="rec/ne.png",[5] ="rec/ve.png",[6] ="rec/am.png"}
I put the elements of this Array into another Array into that have 2 different randoms, like this:
randoms = {[1] = misImagenes[math.random(1,6)],[2] = misImagenes[math.random(1,6)] }
So, I wanna put this randoms of random form, hence, i create an random of the randoms.
randomRan = randoms[math.random(1,2)]
I put the randomRan into the 6 variables, but the images of the variables are always equals.
uno = display.newImageRect(randomRan,340,280)
dos = display.newImageRect(randomRan,340,280)
tres = display.newImageRect(randomRan,340,280)
cuatro = display.newImageRect(randomRan,340,280)
cinco = display.newImageRect(randomRan,340,280)
seis = display.newImageRect(randomRan,340,280)
This variables have the randomRan, but the images are alway equals, i need that the images are differents, 2 differents images in random variables.
Thanks
It looks like what you want to do is commonly called shuffling and filtering an array.
Once you assign randoms[math.random(1,2)] to the randomRan variable, it is going to stay the same no matter what. It isn't like randomRan is going to be random each time it's used. However, if it were a function call, like randomRan(), then that would be a different case, depending on what the function did. A variable, once assigned to, generally stays the same unless changed.
math.randomseed(os.time()) -- Make sure to seed the random number generator.
local function shuffle(t)
local n = #t
while n >= 2 do
-- n is now the last pertinent index
local k = math.random(n) -- 1 <= k <= n
-- Quick swap
t[n], t[k] = t[k], t[n]
n = n - 1
end
return t
end
local misImagenes = {"rec/ro.png", "rec/az.png", "rec/ros.png", "rec/ne.png", "rec/ve.png", "rec/am.png"}
local randomImages = {}
-- Make a copy of misImagenes for randomImages.
for i, v in ipairs(misImagenes) do randomImages[i] = v end
-- Shuffle the new array. This will randomize the order of its contents.
shuffle(randomImages)
-- Since you want only two unique images for a total of six rectangles,
-- we'll have to duplicate and overwrite the other four, randomly.
for i = 1+2, 6 do
randomImages[i] = randomImages[math.random(1, 2)]
end
-- Now to filter the array with newImageRect.
for i=1, #randomImages do
randomImages[i] = display.newImageRect(randomImages[i], 340, 280)
end
-- randomImages now contains all of your randomized image rectangles.
The shuffle algorithm was borrowed from here to show an example of how this could work.
If you are doing
var1 = randomRan
var2 = randomRan
then var1 and var2 will have the same value - randomRan does not get recomputed each time its evaluated. YIf that is what you want, you can repeat the expression you used to initialize randomRan:
var1 = randoms[math.random(1,2)]
var2 = randoms[math.random(1,2)]
and if you want to avoid retyping that ocmplex expression, you can encapsulate it in a function:
--Return a random image
local function randomRan()
return randoms[math.random(1,2)]
end
var1 = randomRan()
var2 = randomRan()
Related
Does someone know a solution to save the key and the values to an table? My idea does not work because the length of the table is 0 and it should be 3.
local newstr = "3 = Hello, 67 = Hi, 2 = Bye"
a = {}
for k,v in newstr:gmatch "(%d+)%s*=%s*(%a+)" do
--print(k,v)
a[k] = v
end
print(#a)
The output is correct.
run for k,v in pairs(a) do print(k,v) end to check the contents of your table.
The problem is the length operator which by default cannot be used to get the number of elements of any table but a sequence.
Please refer to the Lua manual: https://www.lua.org/manual/5.4/manual.html#3.4.7
When t is a sequence, #t returns its only border, which corresponds to
the intuitive notion of the length of the sequence. When t is not a
sequence, #t can return any of its borders. (The exact one depends on
details of the internal representation of the table, which in turn can
depend on how the table was populated and the memory addresses of its
non-numeric keys.)
Only use the length operator if you know t is a sequence. That's a Lua table with integer indexes 1,..n without any gap.
You don't have a sequence as you're using non-numeric keys only. That's why #a is 0
The only safe way to get the number of elements of any table is to count them.
local count = 0
for i,v in pairs(a) do
count = count + 1
end
You can put #Piglet' code in the metatable of a as method __len that is used for table key counting with length operator #.
local newstr = "3 = Hello, 67 = Hi, 2 = Bye"
local a = setmetatable({},{__len = function(tab)
local count = 0
for i, v in pairs(tab) do
count = count + 1
end
return count
end})
for k,v in newstr:gmatch "(%d+)%s*=%s*(%a+)" do
--print(k,v)
a[k] = v
end
print(#a) -- puts out: 3
The output of #a with method __len even is correct if the table holds only a sequence.
You can check this online in the Lua Sandbox...
...with copy and paste.
Like i do.
my problem is that he uses all 3 spawn points instead of only 1 of the 3 that I put there to choose from
YY_Pos = {}
YY_Pos[1] = {m=3017299663, x=1700, y=13154, z=2450}
YY_Pos[2] = {m=3017299663, x=1775, y=12413, z=2436}
YY_Pos[3] = {m=3017299663, x=1775, y=12413, z=2500}
function YY_tmhz_1_OnCreatureDisappear(MapID, InstanceID, Creatur ID, x, y, z)
for i = 1,3 do
local Index_pos = math.random(1,3)
local CreatureID = map.MapCreateCreature(YY_Pos[i].m, InstanceID, 1534207, YY_Pos[i].x, YY_Pos[i].y, YY_Pos[i].z)
end
end
You create a random value Index_pos but you never use it.
Instead you use the loop counter variable i to index your coordinate table.
Also note that the code as is will not use 1 of three coordinates but 3 random coordinates.
You would have to move the math.random call out of the loop if you want to do something 3 times for the same random index.
I have a nested table like so:
t1 ={}
t1[1] = {col1=1,col2=1,col3=1,col4=1}
t1[2] = {col1=1,col2=1,col3=1,col4=1}
t1[3] = {col1=1,col2=1,col3=1,col4=1}
t1[4] = {col1=1,col2=1,col3=1,col4=1}
it's actually much larger with 250 items in t1 and 30 items per nested table so what I want to do is loop through and get sub table values like this:
for i = 2, 4 do
local width = t1[draw.ID].col1 --draw.ID is got elsewhere
end
but changing the number part of .col1 to the i part so when it loops through it gets:
t1[draw.ID].col2
t1[draw.ID].col3
t1[draw.ID].col4
I'm using Lua 5.1.
for i= 2, 4 do
local width = t1[draw.ID]["col" .. i] --draw.ID is got elsewhere
end
Ideally, col would be or would contain an array-like table or sequence. This is a much more scalable way to accomplish what you're trying to do. String concatenation ['col' .. i] to access table keys in the fashion that you'd access them as an array is costly and unnecessary, if it can be avoided. This is especially important if this is something you plan to do often and want to work quickly.
-- Elements of t1 contain tables with cols.
local t1 = {}
t1[1] = {cols = {1,1,1,1}}
t1[2] = {cols = {1,1,1,1}}
t1[3] = {cols = {1,1,1,1}}
t1[4] = {cols = {1,1,1,1}}
for i=2, 4 do
local width = t1[draw.ID].cols[i]
end
-- Elements of t1 are the cols.
local t1 = {}
t1[1] = {1,1,1,1}
t1[2] = {1,1,1,1}
t1[3] = {1,1,1,1}
t1[4] = {1,1,1,1}
for i=2, 4 do
local width = t1[draw.ID][i]
end
Edit: If it's unavoidable that you have to use table keys in the style of ['col' .. i], then the best you could do is to cache them for faster access.
-- Cache all the possible keys that you'll need.
local colkeys = {}
for i=1, 30 do colkeys[i] = 'col' .. i end
for i=2, 4 do
local width = t1[draw.ID][colkeys[i]]
end
This method is anywhere from 4 to 8 times faster than concatenating a string each time that you need to index the table. It's not the ideal solution, but it works if you're stuck with the likes of col1 to col30.
I was working on a script to randomize the data inside of my array but I get and error
that says
unexpected symbol near "#"
When I go to that line, and I remove the "#" I get
attempt to perform arithmetic on local `n' (a table value)
Here is my shuffle function
function shuffle(array)
local array = array
local n = #array
local j
local random = math.random
for i=n-1, 1, -1 do
j = random(i)
array[j],array[i] = array[i],array[j]
end
return array
end
and here is what I am trying to randomize
shuffle(new_players)
for name,character in pairs(new_players) do
if (character.inside == true and character.death == 0) then
local player = getPlayerByName(name, map_copy)
if (player ~= nil) then
addState(player)
break
end
end
end
Here is my array
new_players= { }
new_players[charName] = { death = 0, inside= true }
Any help? If i am doing something completely wrong?
1) Try change charName from string to a number.
2) For shuffle you can use this code:
function swap(array, index1, index2)
array[index1], array[index2] = array[index2], array[index1]
end
function shuffle(array)
local counter = #array
while counter > 1 do
local index = math.random(counter)
swap(array, index, counter)
counter = counter - 1
end
end
If your Lua version is < 5.1 then there is no # operator. Use table.getn instead:
local n = table.getn(array);
(Update) Note that your function, while it does shuffle the items around, it does not really shuffle all elements. Also since you reduce the range with each iteration, you will almost certainly swap the first 10% of your array around multiple times. Now swapping them multiple times is not bad by itself, but that you are, by comparison, almost never swapping the other elements is.
So one option to solve this would be to always use the same range for your random variable. And I would go even further and select two random indexes to swap:
function shuffle(array)
local n, random, j = table.getn(array), math.random
for i=1, n do
j,k = random(n), random(n)
array[j],array[k] = array[k],array[j]
end
return array
end
The other option would be to select random elements from the source array and put them into a new output array:
local rnd,trem,getn,ins = math.random,table.remove,table.getn,table.insert;
function shuffle(a)
local r = {};
while getn(a) > 0 do
ins(r, trem(a, rnd(getn(a))));
end
return r;
end
I am starting to learn Lua from Programming in Lua (2nd edition)
I didn't understand the following in the book. Its very vaguely explained.
a.) w={x=0,y=0,label="console"}
b.) x={math.sin(0),math.sin(1),math.sin(2)}
c.) w[1]="another field"
d.) x.f=w
e.) print (w["x"])
f.) print (w[1])
g.) print x.f[1]
When I do print(w[1]) after a.), why doesn't it print x=0
What does c.) do?
What is the difference between e.) and print (w.x)?
What is the role of b.) and g.)?
You have to realize that this:
t = {3, 4, "eggplant"}
is the same as this:
t = {}
t[1] = 3
t[2] = 4
t[3] = "eggplant"
And that this:
t = {x = 0, y = 2}
is the same as this:
t = {}
t["x"] = 0
t["y"] = 2
Or this:
t = {}
t.x = 0
t.y = 2
In Lua, tables are not just lists, they are associative arrays.
When you print w[1], then what really matters is line c.) In fact, w[1] is not defined at all until line c.).
There is no difference between e.) and print (w.x).
b.) creates a new table named x which is separate from w.
d.) places a reference to w inside of x. (NOTE: It does not actually make a copy of w, just a reference. If you've ever worked with pointers, it's similar.)
g.) Can be broken up in two parts. First we get x.f which is just another way to refer to w because of line d.). Then we look up the first element of that table, which is "another field" because of line c.)
There's another way of creating keys in in-line table declarations.
x = {["1st key has spaces!"] = 1}
The advantage here is that you can have keys with spaces and any extended ASCII character.
In fact, a key can be literally anything, even an instanced object.
function Example()
--example function
end
x = {[Example] = "A function."}
Any variable or value or data can go into the square brackets to work as a key. The same goes with the value.
Practically, this can replace features like the in keyword in python, as you can index the table by values to check if they are there.
Getting a value at an undefined part of the table will not cause an error. It will just give you nil. The same goes for using undefined variables.
local w = {
--[1] = "another field"; -- will be set this value
--["1"] = nil; -- not save to this place, different with some other language
x = 0;
y = 0;
label = "console";
}
local x = {
math.sin(0);
math.sin(1);
math.sin(2);
}
w[1] = "another field" --
x.f = w
print (w["x"])
-- because x.f = w
-- x.f and w point one talbe address
-- so value of (x.f)[1] and w[1] and x.f[1] is equal
print (w[1])
print ((x.f)[1])
print (x.f[1])
-- print (x.f)[1] this not follows lua syntax
-- only a function's has one param and type of is a string
-- you can use print "xxxx"
-- so you print x.f[1] will occuur error
-- in table you can use any lua internal type 's value to be a key
-- just like
local t_key = {v=123}
local f_key = function () print("f123") end
local t = {}
t[t_key] = 1
t[f_key] = 2
-- then t' key actualy like use t_key/f_key 's handle
-- when you user t[{}] = 123,
-- value 123 related to this no name table {} 's handle