The data is not inserted successfully.
Output:
dataHolder.variableNames = []
when it should be :
dataHolder.variableNames = [{'area_12345[<>]6789'}, {'apollo123'}, {'guruX'}, {'ok'}];
% USAGE:
elementNames = {'area_12345[<>]6789', 'apollo123', 'guruX', 'ok'};
elementTypes = {'string', 'specialChar', 'int', 'float'};
elementValues = {'charlie', 'vvv', '09', '123.321'};
dataHolder = dynamicVariableNaming;
str = 'test';
result = dataHolder.ensureCellType(str);
for i = 1:3
dataHolder.addVariables(elementNames(i), elementTypes(i), elementValues(i));
end
dataHolder.variableNames
%%% CLASS
classdef dynamicVariableNaming
%HELLO Summary of this class goes here
% -
properties
variableNames = [];
variableValues = [];
variableTypes = [];
end
methods (Access = public) % (Access = private)
function obj = dynamicVariableNaming (variableName, variableValue, variableType)
% class constructor
if(nargin > 0)
obj.variableNames = variableName;
obj.variableValues = variableValue;
obj.variableTypes = variableType;
end
end
% end
%
% methods (Static = true)
function addVariables (obj, variableName, variableValue, variableType)
obj.variableNames = [obj.variableNames ensureCellType(obj, variableName)];
obj.variableValues = [obj.variableValues ensureCellType(obj, variableValue)];
obj.variableTypes = [obj.variableTypes ensureCellType(obj, variableType)];
end
function cellData = ensureCellType(obj, value)
if (~strcmp(class(value), 'cell'))
cellData = {value};
% cell2string(value);
else
cellData = value;
end
end
end
end
You are not returning the changed opbject from the addVariables method as required when you are working with non-handle objects. Remember, matlab is different in comparison with other reference passing-based languages.
To fix it either make your class enherit from the handle class, or return obj from addVariables
Cant say if there are other problems in the code due to its poor formatting and inability to run in matlab (unbalanced ends, missing constructors, etc.)
Related
I am trying to implement the Kotlin scope function so assigning the variable like type/queue is clear to me but the flush() and startTimer() are not clear wheather I am using them correctly or not.
#KotlinCleanup("use scope function")
var c = note.cards()[0]
c.type = CARD_TYPE_REV
c.queue = QUEUE_TYPE_REV
c.due = (col.sched.today - 8).toLong()
c.factor = STARTING_FACTOR
c.setReps(3)
c.lapses = 1
c.ivl = 100
c.startTimer()
c.flush()
Is this the correct way to use the scope function on this variable ?
var c = note.cards()[0].apply {
type = CARD_TYPE_REV
queue = QUEUE_TYPE_REV
due = (col.sched.today - 8).toLong()
factor = STARTING_FACTOR
setReps(3)
lapses = 1
ivl = 100
startTimer()
flush()
}
I am trying to translate the below javascript "bestSum" memoization function into lua:
const bestSum = (targetSum,numbers,memo ={}) => {
if(targetSum in memo) return memo[targetSum];
if(targetSum === 0 ) return [];
if(targetSum <0)return null;
let shortestCombination = null;
for (let num of numbers) {
const remainder = targetSum - num;
const remainderCombination = bestSum(remainder,numbers,memo);
if (remainderCombination !==null) {
const combination = [...remainderCombination, num];
if (shortestCombination === null || combination.length < shortestCombination.length)
{
shortestCombination = combination;
}
}
}
memo [targetSum] = shortestCombination;
return shortestCombination;
}
sample test cases with correct results:
console.log(bestSum(7,[5,3,4,7])); //[7]
console.log(bestSum(8,[2,3,5])); //[3,5]
console.log(bestSum(8,[1,4,5])); //[4,4]
console.log(bestSum(100,[1,2,5,25])); //[25,25,25,25]
I translated the above javascript into lua as the following:
local function BestSum(target_sum,numbers,memo)
if memo[target_sum] ~= nil then return memo[target_sum] end
if target_sum == 0 then return {} end
if target_sum < 0 then return nil end
local shortest_combination = nil
for i, num in ipairs (numbers) do
local remainder = target_sum - num
local remainder_combination = BestSum(remainder,numbers, memo)
if remainder_combination ~= nil then
local combination = remainder_combination
table.insert(combination,num )
if (shortest_combination == nil) or (#combination < #shortest_combination )then
shortest_combination = combination
end
end
end
memo[target_sum] = shortest_combination;
return shortest_combination;
end
but don't get the desired results for the two last cases...... instead get incorrect results:
BestSum(8,{1,4,5},{})==>{"4","1","4"}
BestSum(150,{5,25},{})==>
{"25","5","5","5","5","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25","5","25"}
The results are not even correct let alone being "best" case??
Can anyone spot where I'm going wrong?
Much appreciated
The problem is with this part of the translation:
local combination = remainder_combination
table.insert(combination, num)
Tables are pass by reference, so this isn't creating a new table, it's just assigning the variable combination to the same table. Modifying combination is just adding more data to remainder_combination.
The JavaScript version is taking care to create a new array, and fills it with the contents of the remainderCombination array (using '...', the spread operator):
const combination = [...remainderCombination, num];
This is the most accurate Lua translation:
local combination = {unpack(remainder_combination)}
table.insert(combination, num)
(Edit: For Lua 5.2+ it's table.unpack)
I Have been browsed on the internet to find an explanation for this problem for 3 days, But I didn't get an explanation to solve this problem. Anyways, I can't solve why "gaming.child.p" return 0 instead of 11. I will be very grateful for your explanation.
Here's the code :
local X = {
p = 1,
diffElementPls = "man"
};
local Y = {__index = X};
function interface()
local o = {};
return setmetatable(o, Y);
end
local w = {
something = "u found me",
child = interface()
};
local noob = {__index = w};
function new()
local o = {};
return setmetatable(o, noob);
end
local gaming = new();
local wd = new()
gaming.something = "noob"
gaming.child.p += 10
wd.child.p = 0
print(gaming.something, wd.something, gaming.child.p, wd.child.p) -- print noob u found me 0 0 instead of noob u found me 11 0
gaming.child and wd.child refer to the same table.
hence modifying wd.child.p also changes the value of gaming.child.p as it is the same variable.
Both wd and gaming don't have a field child. Hence when you index it Lua will refer to their metatable w. So in both cases you're actually modifing w.child.p
I don't know how make classes in lua so I used code which was recommended on forum.
But always only one object works. First one have coordinates x,y and the other object share his coordinates. Can you explain what I´m doing wrong in this code.
Thank you for your advice.
My code:
require("class")
asteroid = class:new()
function asteroid:init(x,y)
asteroid.b = love.physics.newBody(world, x ,y , "dynamic")
asteroid.s = love.physics.newCircleShape(35)
asteroid.f = love.physics.newFixture(asteroid.b, asteroid.s)
end
function love.load()
world = love.physics.newWorld(0, 50, true)
asteroid1= asteroid:new(100,100)
asteroid2= asteroid:new(700,100)
end
function love.update(dt)
world:update(dt)
end
function love.draw()
love.graphics.circle("line", asteroid1.b:getX(),asteroid1.b:getY(), asteroid1.s:getRadius(), 35)
love.graphics.circle("line", asteroid2.b:getX(),asteroid2.b:getY(), asteroid2.s:getRadius(), 35)
end
Recommended code:
__HAS_SECS_COMPATIBLE_CLASSES__ = true
local class_mt = {}
function class_mt:__index(key)
return self.__baseclass[key]
end
class = setmetatable({ __baseclass = {} }, class_mt)
function class:new(...)
local c = {}
c.__baseclass = self
setmetatable(c, getmetatable(self))
if c.init then
c:init(...)
end
return c
end
Here is a demo code for you
local MyClass = {}
MyClass.__index = MyClass
setmetatable(MyClass, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function MyClass.new(init)
local self = setmetatable({}, MyClass)
self.value = init
return self
end
-- the : syntax here causes a "self" arg to be implicitly added before any other args
function MyClass:set_value(newval)
self.value = newval
end
function MyClass:get_value()
return self.value
end
local instance = MyClass(5)
-- do stuff with instance...
I would suggest you to follow these tutorials
http://lua-users.org/wiki/ObjectOrientationTutorial
http://lua-users.org/wiki/TutorialDirectory
The : syntax causes an implicit self to be available as a local, referring to the object instance. But you are assigning to b at class level. Use self.b = instead of asteroid.b = so that the assignment is specific to the instance.
So, I'm trying to write a simple class in Lua for representing CSV fields:
csv_entry = {}
csv_entry.__index = csv_entry
function csv_entry.create(...)
return arg
end
function csv_entry:tostring()
local str = string.char()
for i,v in ipairs(self) do
if i < #self then
str = str .. v
else
str = str .. v .. ", "
end
end
end
function csv_entry:print()
print(self:tostring())
end
But when I try to use this class like this:
c = csv_entry.create("Volvo", 10000, "Eric")
c:print() -- line 25
I get the error message
lua: csv.lua:25: attempt to call method 'print' (a nil value)
And I can't really figure out the issue here. What am I doing wrong?
You probably meant to do is this:
function csv_entry.create(...)
return setmetatable(arg, csv_entry)
end
Your posted version of cvs_entry.create just returns it's arguments packed into a table, so this code:
c = csv_entry.create("Volvo", 10000, "Eric")
c:print()
Is exactly equivalent to this code:
c = {"Volvo", 10000, "Eric"}
c:print()
c doesn't contain a print entry, so c.print returns nil and c:print() fails because you're trying to "call" nil.
Side note: the implicit arg parameter to variadic functions was removed in Lua 5.1 (6 years ago). The correct way to do this now is:
function csv_entry.create(...)
local arg = {...}
return setmetatable(arg, csv_entry)
end
Or simply:
function csv_entry.create(...)
return setmetatable({...}, csv_entry)
end
As long as we're here: you're going to get no output from csv_entry:tostring because it doesn't return anything. Also, if all you're trying to do is to concatenate a bunch of items with comma separators, you can use table.concat:
function csv_entry:tostring()
return table.concat(self, ', ')
end
I rewrite your code to meet what it is for, it runs OK for me:
csv_entry = {}
function csv_entry:create(...)
o = {content = {}}
self.__index = self;
setmetatable(o, self)
for i = 1, arg.n do
o.content[i] = arg[i];
end
return o;
end
function csv_entry:tostring()
local resStr = ""
for i, v in pairs(self.content) do
resStr = resStr .. v;
if i < #(self.content) then
resStr = resStr .. ", "
end
end
return resStr;
end
function csv_entry:print()
print(self:tostring())
end
c = csv_entry:create("Volvo", 10000, "Eric")
c:print()
Like #Mud said, the create(...) in your code is just a regular call and returns all arguments from ..., if you want csv_entry works like a class, then you have to put codes which set metatable and __index into create(...), and return an instance from csv_entry class