Lua Naming a table from function input - function

If I do something wrong with the formatting or anything else, sorry, I don't use this site often.
I'm trying to make a function in lua that with take a name I give it, and create a subtable with that name, and when I tried something like this it just made the absolute name I put in the function's code.
NewSubtable =
function(SubtableName)
Table.SubtableName = {} --Creates a subtable called SubtableName
end
How can I make this create a subtable that is called by the name I give in the function when I use it? Is there an indicator or something to let the code know not to use the name given, but to use the variable assigned when I use the function?
EDIT: So whenever I try this, I get the the result "table index is nil" and it points to the error on line 4
I went and tested this but with a different input type, and it was just my fault. I didn't think that strings would the the value type you'd need for what I'm doing. My problem is solved.
Complete code:
Items = {}
NewWeapon = function(id, name, desc, minDMG, maxDMG)
Items[id] = {}
Items[id].Name = name
Items[id].Desc = desc
Items[id].MinDMG = minDMG
Items[id].MaxDMG = maxDMG
end
NewWeapon(Test, "test", "test", 1, 1)

Table.SubtableName is actually a syntactic sugar for Table['SubtableName']. To use the contents of variable SubtableName use the idom Table[SubtableName].

Related

How to use user defined python function inside a sqlalchemy query filter?

I have a function in python is_valid_id(id) which returns True or False.
I want to use this function in my sqlalchmy query inside filter condition. My query is as below.
result = session.query(tableName).filter(is_valid_id(id) == True).all()
This throwing the following error.
AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'strip'
Can you please tell how to use a user defined function inside sqlalchemy query.
I have tried using func keyword also. That is not working.
Right now you're saying filter by (True == True).all()
This doesn't do anything.
You need to say what you're filtering.
result = session.query(tableName).filter(tableName.columnName == condition).all()
It sounds to me like you should do something like this.
Grab everything, then loop through each object and see if your id returns true.
For example:
table_objects = session.query(tableName).all()
for current_object in table_objects:
current_id = current_object.id
is_current_id_valid = is_valid_id(current_id)
if is_current_id_valid:
print(f'this id is valid: {current_id}')

Writing a function to split a data set into two

First, split the max_hf data set into two groups, Y and N.
def split_data_hf(old_data, new_data, variable, category):
new_data = old_data[old_data.variable == category]
split_data_hf(max_hf, max_hf1, inducted, 'Y')
split_data_hf(max_hf, max_hf2, inducted, 'N')
When I try to run this, I get the error that the variable inducted (which I am trying to pass through) is not defined. Can anyone explain why this is the case?
Theoretically it should work, and if I remove the variable input from the split_data_hf function and then add inducted in place of variable, then it runs just fine.
Anyways, I think I figured it out myself.
Instead of having
old_data[old_data.variable == category]
One should write:
old_data[old_data[variable] == category]
Then, when the input variable is passed, write "...." to pass the argument through.
Thanks!

Calling the function name

As a beginner in Lua, I am sorry if the answer on this is easy.
I was trying to call a function within a code, yet after 2 hours of searching I couldn't find the wanted results. (Maybe I use the wrong search query's?)
Example code
function Test123 ()
SayTest = True
if SayTest = True then
-- This Is where I want to call the function name Test123,
-- yet I can't seem to succeed in this since it is just
-- starting a new function
SystemNotice ( role, function)
end
end
This should be the result:
function Test123 ()
SayTest = True
if SayTest = True then
SystemNotice ( role, 'Test123')
end
end
If anyone can help me out, I would be thankful. If I am still being unclear, just tell me and I will try to describe it better. My excuses for my limited English.
In Lua functions are actually values. That means they do not really have a name, you can only assign them to a variable or table field, but since the value itself has no concept of its name, you can't retrieve it.
That said, with the debug library, you can do this:
function getfname()
return debug.traceback("", 2):match("in function '(.-)'");
end
function bar()
print(getfname())
end
bar(); -- prints bar
foo = bar;
foo() -- prints foo
knerf = {rab = bar};
knerf.rab() -- prints rab
Note that this only works with the default Lua error handler or one that returns the same or very similar output, however you can obviously modify the pattern to suit what you need.
Read this: I would not advise this solution for performance-intensive tasks. Both string matching and the traceback are not really suited for this. Also, obviously the debug library must be enabled so you can actually use the traceback function.
Your function declaration lacks anend.
function Test123 ()
end
Read the functions chapter from the Lua manual. Just for the record, your if will also need an end.
This is a construct that just goes against the Lua philosophy that functions are first class citizens:
a function is just another value, and as such it has no name.
A variable can be assigned a value, thus binding a function to a name.
But that name can change. or a function can have multiple names. Which one to pick?
A better solution would be creating an anonymous function with an upvalue (a closure) instead:
function genTest(name)
return function()
SayTest = true
if SayTest == true then
print ( 'role', name)
end
end
end
Test123 = genTest('Test123')
Test123()
foobar = Test123
foobar()
This creates a function with a bound local variable name (see PiL 6.1 ).

Lua - Execute a Function Stored in a Table

I was able to store functions into a table. But now I have no idea of how to invoke them. The final table will have about 100 calls, so if possible, I'd like to invoke them as if in a foreach loop. Thanks!
Here is how the table was defined:
game_level_hints = game_level_hints or {}
game_level_hints.levels = {}
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
},
[on_scene("scene1")] =
{
talk("hint0"),
talk("hint1"),
talk("hint2")
}
}
end
Aaand the function definitions:
function on_scene(sceneId)
-- some code
return sceneId
end
function talk(areaId)
-- some code
return areaId
end
EDIT:
I modified the functions so they'll have a little more context. Basically, they return strings now. And what I was hoping to happen is that at then end of invoking the functions, I'll have a table (ideally the levels table) containing all these strings.
Short answer: to call a function (reference) stored in an array, you just add (parameters), as you'd normally do:
local function func(a,b,c) return a,b,c end
local a = {myfunc = func}
print(a.myfunc(3,4,5)) -- prints 3,4,5
In fact, you can simplify this to
local a = {myfunc = function(a,b,c) return a,b,c end}
print(a.myfunc(3,4,5)) -- prints 3,4,5
Long answer: You don't describe what your expected results are, but what you wrote is likely not to do what you expect it to do. Take this fragment:
game_level_hints.levels["level0"] = function()
return
{
[on_scene("scene0")] =
{
talk("hint0"),
}
}
end
[This paragraph no longer applies after the question has been updated] You reference on_scene and talk functions, but you don't "store" those functions in the table (since you explicitly referenced them in your question, I presume the question is about these functions). You actually call these functions and store the values they return (they both return nil), so when this fragment is executed, you get "table index is nil" error as you are trying to store nil using nil as the index.
If you want to call the function you stored in game_level_hints.levels["level0"], you just do game_level_hints.levels["level0"]()
Using what you guys answered and commented, I was able to come up with the following code as a solution:
asd = game_level_hints.levels["level0"]()
Now, asd contains the area strings I need. Although ideally, I intended to be able to access the data like:
asd[1][1]
accessing it like:
asd["scene0"][1]
to retrieve the area data would suffice. I'll just have to work around the keys.
Thanks, guys.
It's not really clear what you're trying to do. Inside your anonymous function, you're returning a table that uses on_scene's return value as keys. But your on_scene doesn't return anything. Same thing for talk.
I'm going to assume that you wanted on_scene and talk to get called when invoking each levels in your game_level_hints table.
If so, this is how you can do it:
local maxlevel = 99
for i = 0, maxlevel do
game_level_hints.levels["level" .. i] = function()
on_scene("scene" .. i)
talk("hint" .. i)
end
end
-- ...
for levelname, levelfunc in pairs(game_level_hints.levels) do
levelfunc()
end

lua : passing parameter to other function problem

not sure did anyone ever face this kind of problem. here is my code
in main.lua :
local highScore = require("highScore")
local username = "myName"
local finishedTime = 12345
highScore:InsertHighScore(userName, finishedTime)
in highScore.lua
function InsertHighScore(name,time)
print(name)
print(time)
-- other code
end
it look simple and shouldn't be wrong, but in my console out put it show :
table: 0x19e6340
myName
after a day of testing, i found that before the 2 parameter that i pass, it actually passing another table to me, so do these changes on highScore.lua:
function InsertHighScore(table,name,time)
print(table)
print(name)
print(time)
-- other code
end
so now my "other code" can work nicely, but why it pass me a table before my parameter ?
In Lua, a call to an object/table with a colon instead of a dot indicates that the object/table should be passed into the function as the first parameter (e.g, as a self). If you don't care about that, then call the function with a dot instead:
highScore.InsertHighScore(userName, finishedTime)