How do I convert an integer to a list of indexes in Lua - lua

I'm pretty new to Lua, I'm trying to convert an integer into an array of indexes but cannot find a robust way to do this.
Here's two examples of what I'm trying to achieve:
Input: 0x11
Desired output: [0, 4]
Input: 0x29
Desired output: [0, 3, 5]

This will work if you're on Lua 5.3 or newer:
local function oneBits(n)
local i, rv = 0, {}
while n ~= 0 do
if n & 1 == 1 then
table.insert(rv, i)
end
i = i + 1
n = n >> 1
end
return rv
end

Related

Lua shuffle with repeating cycle

Having some Lua trouble with a a modification of Fisher-Yates shuffle in place. For example, let's say I have a 16 item table (sequence). I want to shuffle integers 1-4 then apply the shuffled pattern in the table to 1-4, 5-8, 9-12, 13-16. So:
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
with a 4 item shuffling pattern of 4,2,3,1 would become:
{ 4, 2, 3, 1, 8, 6, 7, 5, 12, 10, 11, 9, 16, 14, 15, 13 }
The code here is from context and includes the "rising edge" input I am using to reshuffle. If you look at the test pic below you can see that yes, it shuffles each section in place, but it reshuffles each section -- I want the shuffled pattern to repeat.
t = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}
range = 4
local function ShuffleInPlace(t)
for i = #t, 2, -1 do
local j = math.random(1, range)
local k = (math.floor(i/(range+.001)))*range + j
t[i], t[j] = t[j], t[i]
end
end
-- initialize new table for shuffling
if s == nil then s = {} end
-- use gate rising edge to shuffle
if prev == nil then prev = 0 end
if gate > 0 and prev <= 0 then
s = t
ShuffleInPlace(s)
end
prev = gate
Test pic:
LMD, thank you, your helpful reply is uncovering a solution (by creating the shuffled "pattern" sequence first, outside the iterator). (Still some issues with the first value I'm working out. And I might be looking at some biproducts of the not-so-great math.random function, but that's another story). I'm a novice so any suggestions are appreciated!
-- range input is 0 to 1
seqRange = math.floor(range*(#t*.99))
local function ShuffleRange(x)
if rdm == nil then rdm = {} end
for m = 1, x do rdm[m] = m end
for m = #rdm, 2, -1 do
local j = math.random(m)
rdm[m], rdm[j] = rdm[j], rdm[m]
return rdm[m]
end
end
local function ShuffleInPlace(t)
y = ShuffleRange(seqRange)
for i = #t, 2, -1 do
local j = (math.floor(i/(seqRange*1.001)))*seqRange + y
t[i], t[j] = t[j], t[i]
end
end
Here's how I would do it, implementing the simple approach of first generating a series of swaps and then applying that to the sublists of length n:
math.randomseed(os.time()) -- seed the random
local t = {}; for i = 1, 16 do t[i] = i end -- build table
local n = 4 -- size of subtables
local swaps = {} -- list of swaps of offsets (0-based)
for i = 0, n - 1 do
-- Insert swap into list of swaps to carry out
local j = math.random(i, n - 1)
table.insert(swaps, {i, j})
end
-- Apply swaps to every subtable from i to i + n
for i = 1, #t, n do
for _, swap in ipairs(swaps) do
-- Swap: First add offsets swap[1] & swap[2] respectively
local a, b = i + swap[1], i + swap[2]
t[a], t[b] = t[b], t[a]
end
end
print(table.concat(t, ", "))
Example output: 4, 2, 1, 3, 8, 6, 5, 7, 12, 10, 9, 11, 16, 14, 13, 15

How could i loop through every OTHER element in a table in Roblox.lua

I am trying to loop through every other element in an table but I cannot find a way to do so.
Any help is appreciated.
Thank you.
It depends what kind of table you're working with. If you have an array-like table, you can use a simple for-loop :
local t = {1, 2, 3, 4, 5, 6, 7, 8}
-- start at 1, loop until i > the length of t, increment i by 2 every loop
for i = 1, #t, 2 do
local val = t[i]
print(val) -- will print out : 1, 3, 5, 7
end
But if you have a dictionary-like table, you will need something to track which key to skip. You could use a simple boolean to keep track, but be aware that there is no guaranteed order of a dictionary-like table.
local t = {
a = 1,
b = 2,
c = 3,
d = 4,
}
local shouldPrint = true
for k, v in pairs(t) do
-- only print the value when it's true
if shouldPrint then
print(k, v) -- will probably print a, 1 and c, 3
end
-- swap shouldPrint's value every loop
shouldPrint = !shouldPrint
end
Maybe try this
local count = 0
for i = 1 , #table/2 do
table[count + i].value = value
count = count + 1
end
Add to the count as you go down

How do I get the sum of 2 tables in LUA?

x = {1, 2, 3}
y = {4, 5, 6}
z = x + y
I have two tables x and y and just want to create a third one which is just the sum of elements in them. I use the above LUA code in an effort but this gives error input:3: attempt to perform arithmetic on a table value (global 'x')...
Like, I want the result z = {5, 7, 9}
Please suggest functions that will be helpful, or please help me form such a function in LUA.
Thanks
Yes, iterate and check with table.concat()
do...
x = {1, 2, 3}
y = {4, 5, 6}
z = {}
-- First check same table length and if so then add sums to z table
if #x==#y then
for i=1,#x do
z[i]=x[i]+y[i]
end
end
print(table.concat(z,' '))
-- puts out: 5 7 9
...end
You cannot add tables in Lua unless you implement the __add metamethod.
For an element wise sum of two sequences simply do this:
function sumElements(t1,t2)
local result = {}
for i = 1, math.min(#t1, #t2) do
result[i] = t1[i] + t2[i]
end
return result
end
of course you should verify your inputs and think about how you want to deal with mismatching table sizes. Let's say t1 has 3 elements and t2 has 5, will you just have 3 result values or will you add 0 to the remaining 2?

How to convert an array into a 2D matrix in Lua?

I have the following array of numbers.
arr = {3412323450, 8912745671, 3212367894}
I want to convert it into a simple two-dimensional matrix.
mat = {
{3, 4, 1, 2, 3, 2, 3, 4, 5, 0},
{8, 9, 1, 2, 7, 4, 5, 6, 7, 1},
{3, 2, 1, 2, 3, 6, 7, 8, 9, 4}
}
Initially, I would iterate over arr, convert it into a string, then split the string, iterate over each string char and convert it back to number storing every row and number in mat accordingly. This would be really ugly.
Is there a more conventional method to convert an array into a matrix in
Lua?
Is there a luarock package that people use frequently to convert an array to a matrix?
Personally I think converting to a string and grabbing all of the digits is far prettier than the alternatives (massively dividing by 10, or any other elaborate means you can think of). This is especially true if you wrap the operations up in functions, so your conversions are not constantly appearing throughout your code.
function Digits(n)
local digits = {}
for d in tostring(n):gmatch('%d') do
digits[#digits+1] = tonumber(d)
end
return digits
end
function ArrayToMatrix(array)
local matrix = {}
for i,v in ipairs(array) do
matrix[i] = Digits(v)
end
return matrix
end
Ok, here is my try.
arr = {3412323450, 8912745671, 3212367894}
function arr2matrix(arr)
local mat = {}
for i, row in ipairs(arr) do
mat[i] = {}
local j = 0
row_str = string.gsub(row, '%d', '%0 ')
for c in string.gmatch(row_str, '%S') do
j = j + 1
mat[i][j] = tonumber(c)
end
end
return mat
end
-- checking the result
m = arr2matrix(arr)
for i=1, #m do
for j=1, #m[i] do
io.write(m[i][j]..',')
end
io.write('\n')
end
Running the above gives:
3,4,1,2,3,2,3,4,5,0,
8,9,1,2,7,4,5,6,7,1,
3,2,1,2,3,6,7,8,9,4,

Does lua have something like python's slice

Like in python I can use slice. Like following
b=[1,2,3,4,5]
a=b[0:3]
Can I do that kind of operation in Lua without a loop. Or Loop is the most efficient way to do that
By creating a new table using the result of table.unpack (unpack before Lua 5.2):
for key, value in pairs({table.unpack({1, 2, 3, 4, 5}, 2, 4)}) do
print(key, value)
end
This generates...
1 2
2 3
3 4
(Tested in Lua 5.3.4 and Lua 5.1.5.)
There's no syntax sugar for doing this, so your best bet would be doing it via a function:
function table.slice(tbl, first, last, step)
local sliced = {}
for i = first or 1, last or #tbl, step or 1 do
sliced[#sliced+1] = tbl[i]
end
return sliced
end
local a = {1, 2, 3, 4}
local b = table.slice(a, 2, 3)
print(a[1], a[2], a[3], a[4])
print(b[1], b[2], b[3], b[4])
Keep in mind that I haven't tested this function, but it's more or less what it should look like without checking input.
Edit: I ran it at ideone.
xlua package has table.splice function. (luarocks install xlua)
yourTable = {1,2,3,4}
startIndex = 1; length = 3
removed_items, remainder_items = table.splice(yourTable, startIndex, length)
print(removed_items) -- 4
print(remainder_items) -- 1,2,3
see: https://github.com/torch/xlua/blob/master/init.lua#L640

Resources