Name a Table with a Variable in LUA (LÖVE Engine)? - dynamic

Basically:
I am making a game in the LÖVE Engine where you click to create blocks
Every time you click, a block gets created at your Mouse X and Mouse Y
But, I can only get one block to appear, because I have to name that block (or table) 'object1'
Is there any way to create table after table with increasing values? (like object1{}, object2{}, object3{}, etc... But within the main table, 'created_objects')
But only when clicked, which I suppose rules out the looping part (but if it doesn't please tell me)
Here's my code so far, but it doesn't compile.
function object_create(x, y, id) **--Agruments telling the function where the box should spawn and what the ID of the box is (variable 'obj_count' which increases every time a box is spawned)**
currobj = "obj" .. id **--Gives my currently created object a name**
crob.[currobj] = {} **--Is supposed to create a table for the current object, which holds all of its properties. **
crob.[currobj].body = love.physics.newBody(world, x, y, "dynamic")
crob.[currobj].shape = love.physics.newRectangleShape(30, 30)
crob.[currobj].fixture = love.physics.newFixture(crob.[currobj].body, crob.[currobj].shape, 1) **--The properties**
crob.[currobj].fixture:setRestitution(0.3)
But what should I replace [currobj] with?
Solved
Found what I was looking for. Here's the code if people are wondering:
function block_create(x, y, id) --(the mouse x and y, and the variable that increases)
blocks[id] = {}
blocks[id][1] = love.physics.newBody(world, x, y, "dynamic")
blocks[id][2] = love.physics.newRectangleShape(45, 45)
blocks[id][3] = love.physics.newFixture(blocks[id][1], blocks[id][2])
blocks[id][3]:setRestitution(0.2)
blocks[id][4] = math.random(0, 255) --The Color
blocks[id][5] = math.random(0, 255)
blocks[id][6] = math.random(0, 255)
blockcount = blockcount + 1

i would probably do something like this.
local blocks = {} -- equivalent of your crob table
function create_block(x, y)
local block = funcToCreateBlock() -- whatever code to create the block
table.insert(blocks, block)
return block
end
if you wanted to get a reference to the block you just created with the function, just capture it.
-- gives you the new block, automatically adds it to the list of created blocks
local new_block = create_block(0, 10)
that sticks block objects in your block table and automatically gives each one a numeric index in the table. so if you called create_block() 3 times for 3 different mouse clicks, the blocks table would look like this:
blocks = {
[1] = blockobj1,
[2] = blockobj2,
[3] = blockobj3
}
you could get the second block obj from the blocks table by doing
local block2 = blocks[2]
or you could loop over all the blocks in the table using pairs or ipairs
for idx, block in pairs(blocks) do
-- do something with each block
end
sorry if this doesn't exactly answer your question. but from what you wrote, there didn't seem to be a real reason why you'd need to name the blocks anything specific in the crob table.

If you want those tables to be global, then you can do something like:
sNameOfTable = "NAME"
_G[sNameOfTable] = {1,2}
and then you will have a table variable NAME as depicted here (Codepad).
Otherwise, if you want it to be a child to some other table, something like this would also do:
tTbl = {}
for i = 1, 20 do
local sName = string.format( "NAME%02d", i )
tTbl[sName] = {1,2}
end
for i, v in pairs(tTbl) do
print( i, v )
end
Don't worry about the unsorted output here(Codepad). Lua tables with indexes need not be sorted to be used.

Related

Print multiple data sets in a range

I've made a small program that is supposed to read data in a range input it into an object oriented program, and then return the full data set. the issue is that when I run the file it only return data on the third procedure
I tried printing other procedure sets but idk how to do that, i'm thinking this will only work if i replace the procedures from generic to specific. as in instead of Procedure name for all of them procedures 1, 2, and 3
for i in range (3):
procedure_name = ('Physical Exam')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Irvine')
charge = ('$ 250.00')
procedure_name = ('X-ray')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Jamison')
charge = ('$ 500.00')
procedure_name = ('Blood test')
date_of = ("Nov 6th 2022")
doctor = ('Dr. Smith')
charge = ('$ 200.00')
procedure = HW6_RODRIGUEZ_1.Procedure(procedure_name,date_of,doctor,charge)
print(f'Procedure {i+1}')
print(procedure)
print(i, end=" ")
if name == 'main':
main()
So, I think you may have misunderstood some things when it comes to variables, OOP and looping.
When you define a variable, that variable is set to the last value it is assigned. So if you have the following code:
a = 1
a = 2
a = 3
The final value of the variable 'a' will be 3, as that is the last value it is assigned.
As for loops, whatever you have written in a for loop will be repeated for a specified number of times. This means if you want to write a loop that prints "hello" 5 times, you'd write the following:
for i in range(5):
print("hello")
What your loop is essentially doing is overwriting the same 3 variables 3 times over, this won't be assigning new values to an object.
When it comes to creating an object that you assign variable to, you need to first write the code for your class. Your class can have attributes like the variables you've stated. It could look something like this:
class procedure:
def __init__(self, procedure_name, date_of, doctor, charge):
self.procedure_name = procedure_name
self.date_of = date_of
self.doctor = doctor
self.charge = charge
Now, to set up a procedure object, you just assign a variable to procedure with the desired variables as parameters, like so:
new = procedure('X-ray','Nov 6th 2022','Dr. Jamison','$ 500.00')
And to access a variable, you just need to write procedureName.attribute. For example, using the object I just set up:
print(new.doctor)
Would output 'Dr. Jamison'.
If you want to store a bunch of them, I would recommend storing them in a list or a dictionary, depending on how you want to look them up.
I hope this helps! If you are new to programming, I would recommend some simpler programs such as a program that prints the nursery rhyme 10 green bottles using loops, or maybe making a quiz.
Best of luck.

How to Optimize an Overuse of If Statements in Roblox Studio

The goal of this code is to spawn a ball "GlowyBall" in 1 of 5 preset locations randomly. This script activates when a player hits a button. The ball also needs to spawn as 1 of 3 colors randomly. The code works for the most part, but I am struggling when it comes to making this code optimized. I don't know which datatype I should or even can use to replace these if statements. I am just trying to learn different avenues that can be taken. The reason this code needs to be optimized is that it could be used thousands of times per minute, and I don't want the game to be held back by the code.
...
-- Says that there will be 3 colors
local ColorRange = 3
-- Says that there will be 5 spawn locations
local range = 5
-- Makes the code run continuously
while true do
local ColorNumber = math.random(1, ColorRange)
local Number = math.random(1, range)
-- Chooses the random color
if ColorNumber == 1 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball1.Color = Color3.new(1, 0, 0)
end
if ColorNumber == 2 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball2.Color = Color3.new(0, 1, 0)
end
if ColorNumber == 3 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball3.Color = Color3.new(0, 0, 1)
end
-- Chooses which ball will get cloned
if Number == 1 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball1
end
if Number == 2 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball2
end
if Number == 3 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball3
end
if Number == 4 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball4
end
if Number == 5 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball5
end
wait(.6)
local Clone = ClonePart:Clone()
script.Parent.ClickDetector.MouseClick:connect(function()
Clone.Parent = game.Workspace
Clone.Anchored = false
end)
end
...
I am fairly new to programming as a whole so feel free to teach me a few things, thanks.
Instances in Roblox can be accessed in a few different ways; the most common is dot notation (eg. game.Workspace.Part). It's also possible to access instances like items in a table (eg. game["Workspace"]["Part"]). This is useful when accessing an instance with a space in its name, or to add something to the start/end of a string before accessing it.
The if statements for choosing which ball to clone can then be reduced to the following:
-- Chooses which ball will get cloned
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1["Glowyball" .. Number] -- Add Number to the end of "Glowyball" before accessing it
The same could be done with choosing the random color, as well as substituting multiple if statements for one if-elseif statement could make the code more readable.
-- Chooses the random color
local Glowyball = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1["Glowyball" .. ColorNumber]
if ColorNumber == 1 then
Glowyball.Color = Color3.new(1, 0, 0)
elseif ColorNumber == 2 then
Glowyball.Color = Color3.new(0, 1, 0)
elseif ColorNumber == 3 then
Glowyball.Color = Color3.new(0, 0, 1)
end
Heliodex did a good job explaining how to simplify finding the instances, but you could take it a step further and remove the if-statements entirely by replacing them with arrays.
Typically, from a general programming standpoint, when you find that you have a lot of very similar if-statements, the solution is to use a switch-statement instead of if-elseif chains. Switch statements allow you to define a bunch of possible cases and when it executes, it will jump specifically to the case that matches. However, neither lua nor luau support switch statements, but we can get the benefit of switch-statements.
Since you are using random numbers already, you can pre-define your colors into an array and have the random number simply pick an index to use...
-- make some colors to pick from
local colors = {
Color3.new(1, 0, 0),
Color3.new(0, 1, 0),
Color3.new(0, 0, 1),
}
-- Set up the list of spawn locations
local locationGroup = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1
local spawnLocations = {
locationGroup.Glowyball1,
locationGroup.Glowyball2,
locationGroup.Glowyball3,
locationGroup.Glowyball4,
locationGroup.Glowyball5,
}
-- could this be simplified to ...?
-- local spawnLocations = locationGroup:GetChildren()
-- when someone clicks the button, spawn the part
script.Parent.ClickDetector.MouseClick:Connect(function()
-- choose a color and spawn location
local colorNumber = math.random(1, #colors)
local spawnNumber = math.random(1, #spawnLocations)
local clonePart = spawnLocations[spawnNumber]
local color = colors[colorNumber]
-- spawn it
local clone = clonePart:Clone()
clone.Color = color
clone.Parent = game.Workspace
clone.Anchored = false
end)
The advantage of this approach is that you can simply add more colors and spawn locations to those arrays, and the rest of your code will still work.

Web2py - SQLFORM.smartgrid: how to retrieve field name and value before submission

I use smartgrid with 'in the grid' edition of values. To do this, I use the .represent function to add the row_id to the variable name, so that I can retrieve what to update in request.post_vars, where I can retrieve the list of filed name, ids, with the submitted value.
But I'd like to identify what has been changed by the user in the smartgrid without making an additional I/O in the DB. Is there a global variable where the form fields and initial values are recorded before user change ? Or a function to extract form fields and values before sending it to the view?
db.define_table('cny',Field('f_cny'))
def tst():
tb = db.cny
if len(request.post_vars) >0:
d = {}
for k,v in request.post_vars.iteritems():
(f,sep,r) = k.partition('_r_')
if r:
if not r in d:
d[r] = {}
d[r][f] = v #should only be done if d[r][f] was changed!!!
for r in d:
if len(d[r]):
db(tb.id==r).update(**d[r])
tb.f_cny.represent=lambda v,r:string_widget(tb.f_cny, v, **{'_name':'f_cny_r_%s' % r.id})
f = SQLFORM.smartgrid(tb,
linked_tables=[],
selectable=(lambda ids:redirect(URL(request.controller,request.function,args=request.args))))
return dict(f=f)

Load multiple Excel sheets using For loop with QlikView

I want to load data from two different Excel files, and use them in the same table in QlikView.
I have two files (DIVISION.xls and REGION.xls), and I'm using the following code:
let tt = 'DIVISION$' and 'REGION$';
FOR Each db_schema in 'DIVISION.xls','REGION.xls'
FOR Each v_db in $(tt)
div_reg_table:
LOAD *
FROM $(db_schema)
(biff, embedded labels, table is $(v_db));
NEXT
NEXT
This code works fine, and does not show any error, but I don't get any data, and I don't see my new table (div_reg_table).
Can you help me?
The main reason that your code does not load any data is due to the form of the tt variable.
When your inner loop executes, it evaluates tt (denoted by $(tt)), which then results in the evaluation of:
'DIVISION$' AND 'REGION$'
Which results in null, since these are just two strings.
If you change your statement slightly, from LET to SET and remove the AND, then the inner loop will work. For example:
SET tt = 'DIVISION$', 'REGION$';
However, this also now means that your inner loop will be executed for each value in tt for both workbooks. This means that unless you have a REGION sheet in your DIVISION workbook, then the load will fail.
To avoid this, you may wish to restructure your script slightly so that you have a control table which details the files and tables to load. An example I prepared is shown below:
FileList:
LOAD * INLINE [
FileName, TableName
REGION.XLS, REGION$
DIVISION.XLS, DIVISION$
];
FOR i = 0 TO NoOfRows('FileList') - 1
LET FileName = peek('FileName', i, 'FileList');
LET TableName = peek('TableName', i, 'FileList');
div_reg_table:
LOAD
*
FROM '$(FileName)'
(biff, embedded labels, table is '$(TableName)');
NEXT
If you have just two files DIVISION.XLS and REGION.XLS then it may be worth just using two separate loads one after the other, and removing the for loop entirely. For example:
div_reg_table:
LOAD
*
FROM [DIVISION.XLS]
(biff, embedded labels, table is DIVISION$)
WHERE DivisionName = 'AA';
LOAD
*
FROM [REGION.XLS]
(biff, embedded labels, table is REGION$)
WHERE RegionName = 'BB';
Don't you need to make the noofrows('Filelist') test be 1 less than the answer.
noofrows('filelist') will evaluate to 2 so you will get a loop step for 0,1 and 2. So 2 will return a null which will cause it to fail.
I did it like this:
FileList:
LOAD * INLINE [
FileName, TableName
REGION.XLS, REGION
DIVISION.XLS, DIVISION
];
let vNo= NoOfRows('FileList')-1;
FOR i = 0 TO $(vNo)
LET FileName = peek('FileName', i, 'FileList');
LET TableName = peek('TableName', i, 'FileList');
div_reg_table:
LOAD
*,
$(i) as I,
FileBaseName() as SOURCE
FROM '$(FileName)'
(biff, embedded labels, table is '$(TableName)');
NEXT

Error Handling with Live Data Matlab

I am using a live data API that is returning the next arriving trains. I plan on giving the user the next 5 trains arriving. If there are less than 5 trains arriving, how you handle that? I am having trouble thinking of a way, I was thinking a way with if statements but don't know how I would set them up.
time1Depart = dataReturnedFromLiveAPI{1,1}.orig_departure_time;
time2Depart = dataReturnedFromLiveAPI{1,2}.orig_departure_time;
time3Depart = dataReturnedFromLiveAPI{1,3}.orig_departure_time;
time4Depart = dataReturnedFromLiveAPI{1,4}.orig_departure_time;
time5Depart = dataReturnedFromLiveAPI{1,5}.orig_departure_time;
time1Arrival = dataReturnedFromLiveAPI{1,1}.orig_arrival_time;
time2Arrival = dataReturnedFromLiveAPI{1,2}.orig_arrival_time;
time3Arrival = dataReturnedFromLiveAPI{1,3}.orig_arrival_time;
time4Arrival = dataReturnedFromLiveAPI{1,4}.orig_arrival_time;
time5Arrival = dataReturnedFromLiveAPI{1,5}.orig_arrival_time;
The code right now uses a matrix that goes from 1:numoftrains but I am using just the first five.
It's a bad practice to assign individual value to a separate variable. Better if you pass all related values to a vector or cell array depending on class of orig_departure_time and orig_arrival_time.
It looks like dataReturnedFromLiveAPI is a cell array of structures. Then you can do:
timeDepart = cellfun(#(x), x.orig_departure_time, ...
dataReturnedFromLiveAPI(1,1:min(5,size(dataReturnedFromLiveAPI,2))), ...
'UniformOutput',0 );
timeArrival = cellfun(#(x), x.orig_arrival_time, ...
dataReturnedFromLiveAPI(1,1:min(5,size(dataReturnedFromLiveAPI,2))), ...
'UniformOutput',0 );
Then you how to access the values one by one as
time1Depart = timeDepart{1};
If orig_departure_time and orig_arrival_time are numeric scalars, you can use ...'UniformOutput',1.... You will get output as a vector and can get single values with timeDepart(1).