what is the pointer to pointer equivalent in lua - pointers

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

Related

Lua 2d array defined in object uses pass by reference

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

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)
}

How efficiently to convert one dimensional array to two dimensional array in swift3

What is the efficient way to convert an array of pixelValues [UInt8] into two dimensional array of pixelValues rows - [[UInt8]]
You can write something like this:
var pixels: [UInt8] = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15]
let bytesPerRow = 4
assert(pixels.count % bytesPerRow == 0)
let pixels2d: [[UInt8]] = stride(from: 0, to: pixels.count, by: bytesPerRow).map {
Array(pixels[$0..<$0+bytesPerRow])
}
But with the value semantics of Swift Arrays, all attempt to create new nested Array requires copying the content, so may not be "efficient" enough for your purpose.
Re-consider if you really need such nested Array.
This should work
private func convert1Dto2DArray(oneDArray:[String], stringsPerRow:Int)->[[String]]?{
var target = oneDArray
var outOfIndexArray:[String] = [String]()
let reminder = oneDArray.count % stringsPerRow
if reminder > 0 && reminder <= stringsPerRow{
let suffix = oneDArray.suffix(reminder)
let list = oneDArray.prefix(oneDArray.count - reminder)
target = Array(list)
outOfIndexArray = Array(suffix)
}
var array2D: [[String]] = stride(from: 0, to: target.count, by: stringsPerRow).map {
Array(target[$0..<$0+stringsPerRow])}
if !outOfIndexArray.isEmpty{
array2D.append(outOfIndexArray)
}
return array2D
}

How to use wildcard string in systemverilog case statement

Case #1:
module try;
string inp = "my_var";
initial begin
$display("Here we go!");
case (inp)
"my_var" : $display("my_var");
default : $display("default");
endcase
end
endmodule
Output is my_var
Case #2
module try;
string inp = "my_var";
initial begin
$display("Here we go!");
case (inp)
"*var*" : $display("*var*");
default : $display("default");
endcase
end
endmodule
Output is default.
Is it possible to get a hit with wildcard search in a case statement?
SystemVerilog does not have any string regular expression matching methods built into the standard. The UVM has a package that has a uvm_re_match() function. You can import the UVM package to get access to this function even if you do not use any other UVM testbench features. Some simulators, such as ModelSim/Questa have these routines built in as an extension to SystemVerilog so that you can do
module try;
string inp = "my_var";
initial begin
$display("Here we go!");
case (1)
inp.match("*var*") : $display("*var*");
default : $display("default");
endcase
end
endmodule
I found a work-around :
function string match(string s1,s2);
int l1,l2;
l1 = s1.len();
l2 = s2.len();
match = 0 ;
if( l2 > l1 )
return 0;
for(int i = 0;i < l1 - l2 + 1; i ++)
if( s1.substr(i,i+l2 -1) == s2)
return s2;
endfunction
module try;
string target_id = "abc.def.ddr4_0";
string inp = "ddr4_0";
string processed_inp;
initial begin
$display("Here we go!");
for(int i=0;i<2;i++) begin
if (i == 1)begin
inp = "ddr4_1";
target_id = "abc.def.ddr4_1";
end
processed_inp = match(target_id, inp);
$display("input to case = %0s", processed_inp);
case (processed_inp)
"ddr4_0" : $display("ddr4_0 captured!");
"ddr4_1" : $display("ddr4_1 captured!");
default : $display("default");
endcase
end
end
endmodule
Output:
Here we go!
input to case = ddr4_0
ddr4_0 captured!
input to case = ddr4_1
ddr4_1 captured!
PS : Found this solution on the www.
Cannot find the link right now. Will post the reference soon.

Correct way to access Multi-Dimensional Array with string indexes in Lua?

I'm trying to have a good access to multi-dimensional arrays with string indexes in Lua, here's basically what I'm trying to do:
rules =
{
{"S_RIGHT", "A_STOP", "S_RESULT"},
}
matrix = {}
for _,v in pairs(rules) do
if( matrix[ v[1] ] == nil ) then
matrix[ v[1] ] = {}
end
matrix[ v[1] ][ v[2] ] = v[3]
end
-- results in error ( attempt to index field 'S_NO' a nil value)
var = matrix["S_NO"]["S_RESULT"]
assert(var == nil, "Var should be nil")
A way to do it but quite verbose is:
var = matrix["S_NO"]
if var ~= nil then
var = var["S_RESULT"]
end
assert(var == nil, "Var should be nil")
Is there a way to make the first case to work ? ( less verbose )
Ok,
Found the answer.
If matrix is going to be read-only a correct approach would be:
local empty = {}
setmetatable(matrix, {__index=function() return empty end})
If I would like to allow writes and it's specifically two levels of tables, I could do:
setmetatable(matrix, {__index=function(t,k) local new={} rawset(t,k,new) return new end}
Hope this helps!

Resources