Lua 2d array defined in object uses pass by reference - multidimensional-array

I have the following object:
local Game = {}
function Game:new(aNumberOfPlayers, aPlayer1, aPlayer2)
self.NumberOfPlayers = aNumberOfPlayers
self.Player1 = aPlayer1
self.Player2 = aPlayer2
self.Id = HttpService:GenerateGUID(true)
self.Status = "Waiting"
self.Moves = {}
self.Position = GetInitialGamePosition()
return self
end
local Square = {}
function Square:new(x, y, index, color)
self.X = x
self.Y = y
self.Index = index
self.Color = color
return self
end
That uses following function to intialize the 2d array for Position
function GetInitialGamePosition()
local mt = {} -- create the matrix
for i=1,15 do
mt[i] = {}
for j=1,15 do
mt[i][j] = Square:new(i,j,GetIndexFromRowColumn(i,j),nil)
end
end
return mt
end
Problem here is that since tables pass by reference each element of the 2d array ends up being the same. In other words when i iterate over a Position every element has same row, column, and index. Not sure what the best way to get around this is?

function Square:new(x, y, index, color)
local o = {}
o.X = x
o.Y = y
o.Index = index
o.Color = color
setmetatable(o, self)
self.__index = self
return o
end

Related

Error map-functions.lua:42: bad argument #2 to 'draw' (Quad expected, got nil) , any idea what's wrong?

I'm very new to love and lua and I don't know why I keep getting this message, any ideas? here's my code, hope you guys know what I could do.
in maps-functions.lua
function loadMap(path)
love.filesystem.load(path)()
end
function newMap(tileW, tileH, tilesetPath, tileString, quadInfo)
TileW = tileW
TileH = tileH
Tileset = love.graphics.newImage(tilesetPath)
local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight()
Quads = {}
for _,info in ipairs(quadInfo) do
-- info[1] = the character, info[2] = x, info[3] = y
Quads[info[1]] = love.graphics.newQuad(info[2], info[3], TileW, TileH, tilesetW, tilesetH)
end
TileTable = {}
local width = #(tileString:match("[^\n]+"))
for x = 1,width,1 do TileTable[x] = {} end
local x,y = 1,1
for row in tileString:gmatch("[^\n]+") do
assert(#row == width, 'Map is not aligned: width of row ' .. tostring(y) .. ' should be ' .. tostring(width) .. ', but it is ' .. tostring(#row))
x = 1
for tile in row:gmatch(".") do
TileTable[x][y] = tile
x = x + 1
end
y=y+1
end
end
function drawMap()
for x,column in ipairs(TileTable) do
for y,char in ipairs(column) do
love.graphics.draw(Tileset, Quads[ char ] , (x-1)*TileW, (y-1)*TileH)
end
end
end
Perhaps it has something to do with the map I drew or the image?

Creating Expression Tree Kotlin

Hi my task is to recursively create an expression tree from a List input.
ex. ("+", 2, 3)
"+"
/ \
2 3
I know my recursion is off, but I can't figure out how to make it work. I've been at it for longer than I'm proud to admit. Any insight is appreciated! This is what I have so
fun TreeBuild(input:List<Any>): Pair<Tree, List<Any>>{
var tree = Tree(input.get(0), Unit, Unit)
var list = input
System.out.println(list)
if(input.size == 1 ){
list = list.drop(1)
return Pair(Tree(input.get(0), Unit, Unit), list)
}
var flag: Boolean = (input.get(0) is Int)
if (!flag){
list = list.drop(1)
tree.left = TreeBuild(list).first
list = list.drop(1)
tree.right = TreeBuild(list).first
}
return Pair(tree, list)
}

what is the pointer to pointer equivalent in lua

I know that you can use tables in a similar way to pointers in lua. That being said, what would pointers to pointers look like? Would they look something like dp = {p = {}}? if so what would the equivalent to the c code below be in lua?
void InsertItem(node **head, node *newp){
node **dp = head;
while((*dp) && (*dp)->value > newp->value
{
dp = &(*dp)->next;
}
newp->next = *dp;
*dp = newp;
}
Yes, double pointer may be translated to Lua as nested table.
local function InsertItem(head, newitem)
while head.next and head.next.value > newitem.value do
head = head.next
end
newitem.next = head.next
head.next = newitem
end
-- Typical Usage:
local head = {}
InsertItem(head, {value = 3.14})
InsertItem(head, {value = 42})
InsertItem(head, {value = 1})
-- Now the data is the following:
-- head = {next = elem1}
-- elem1 = {next = elem2, value = 42 }
-- elem2 = {next = elem3, value = 3.14}
-- elem3 = { value = 1 }
The big difference between C pointers and Lua tables is that in C, you can take the address of a variable and pass it to a function to modify it. You can't do that in Lua, but the function could always return the modified value.
Would they look something like dp = {p = {}}?
Yes, that's about as close as close as you can get to a pointer to a pointer in Lua.
if so what would the equivalent to the c code below be in lua?
Linked lists tend to work more smoothly with recursion:
local function InsertItem(head, newp)
if not head or head.value <= newp.value then
newp.next = head
return newp
end
head.next = InsertItem(head.next, newp)
return head
end

Saving variable get_pdf() into fields.binary

I want to save a variable automatically into a fields.binary (email_attachment_file) from get_pdf function.
My codes below here:
class example_example(models.Model):
email_attachment_file = fields.Binary('Data (.txt,.pdf)')
email_filename = fields.Char('Filename')
def generate(self,etc..):
report_name = "report_name_template"
datas = {
'ids':[],
'model' : etc,
'form' : etc
'context': context
}
moddelReport = self.pool.get('report')
alpha = modelReport.get_pdf(cr, uid,[],report_name,None,datas,context=context)
#alpha = base64.decodestring(alpha)
#alpha = alpha.decode('unicode_escape').encode('utf-8')
# --------- how to save alpha variable into fields.binary
And, is there something wrong modelReport.get_pdf function ?
Use encodestring() instead of decodestring().
report_obj = self.pool.get('report')
data = modelReport.get_pdf(cr, uid,[],report_name,None,datas,context=context)
self.email_attachment_file = base64.encodestring(data)

Serialization fails with custom Torch class

Serialization can fails with a class object created containing __pairs:
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
The following returns:
test
nil
The engine behind the torch.serialization is located in the File-class. The File:writeObject us the key function. For the above example the action for a Torch class starts at line 201 with the:
elseif typeidx == TYPE_TORCH then
The type is identified in the File:isWritableObject.
One could probably implement the metatable function write but in the above example the problem was non-torch metatable function __pairs that should be __pairs__ (see torch.getmetatable):
test = torch.class('test')
function test:__init()
self.data = {}
end
function test:__pairs__(...)
return pairs(self.data, ...)
end
function test:get_data()
print(self.data)
end
a = test.new()
a.data = {"asdasd"}
b = torch.serialize(a)
c = torch.deserialize(b)
print(torch.typename(c))
print(c:get_data())
This gives the expected:
test
{
1 : "asdasd"
}

Resources