Is it possible to check if some object is really element of specified table? I tried to use debug.getfenv(o) but didn't work.
someTable = {}
someTable.someValue = "Some String"
--gettable(someTable.someValue)
--so that could return table that stores someValue: someTable
getfenv is so named because it returns a function's environment. Because only functions have environments.
Values in Lua have no particular knowledge of which tables that they're in. If you need to know that, you'll have to keep track of it yourself.
Related
I am new to Lua, and this is an elementary question.
I a Lua script, I am querying the Postgress DB for two records via Freeswitch dbh.
I am able to set the first value as a local variable.
I am stuck at how to set the second value as a variable.
local dbh = Database.new('system');
local settings = Settings.new(dbh, A, B);
local sql = "SELECT A, B FROM TABLE WHERE A = '" .. A.."'";
local A = dbh:first_value(sql); --this gets saved correctly
local B = WHAT DO PUT HERE? ; -- Perhaps, I need to create an array instead?
dbh:release()
If you only want a specific row you should do this in the SQL command.
Alternatively you can query the entire table and run through the rows of the result.
I don't know freeswitch but that's what I found here:
https://freeswitch.org/confluence/display/FREESWITCH/Lua+API+Reference
dbh:query("query", function()) takes the query as a string and an optional Lua callback function that is called on each row returned by
the db. The callback function is passed a table representation of the
current row for each iteration of the loop.
Syntax of each row is: { ["column_name_1"] = "value_1", ["column_name_2"] = "value_2" }.
If you (optionally) return a number other than 0 from the
callback-function, you'll break the loop.
In order to use this you should learn how to define functions and how to use function values. Then it should be obvious what to do.
Maybe there is also a function that returns the query result as a table. At least that is the case for many other database interfaces. Ideally you should read the manual of the freeswitch Lua API first. Then you know what commands exist. Together with the Lua manual you'll know how to use them.
Our task is create a table, and read values to the table using a loop. Print the values after the process is complete. - Create a table. - Read the number of values to be read to the table. - Read the values to the table using a loop. - Print the values in the table using another loop. for this we had written code as
local table = {}
for value in ipairs(table) do
io.read()
end
for value in ipairs(table) do
print(value)
end
not sure where we went wrong please help us. Our exception is
Input (stdin)
3
11
22
abc
Your Output (stdout)
~ no output ~
Expected Output
11
22
abc
Correct Code is
local table1 = {}
local x = io.read()
for line in io.lines() do
table.insert(table1, line)
end
for K, value in ipairs(table1) do
print(value)
end
Let's walk through this step-by-step.
Create a table.
Though the syntax is correct, table is a reserved pre-defined global name in Lua, and thus cannot should not be declared a variable name to avoid future issues. Instead, you'll need to want to use a different name. If you're insistent on using the word table, you'll have to distinguish it from the function global table. The easiest way to do this is change it to Table, as Lua is a case-sensitive language. Therefore, your table creation should look something like:
local Table = {}
Read values to the table using a loop.
Though Table is now established as a table, your for loop is only iterating through an empty table. It seems your goal is to iterate through the io.read() instead. But io.read() is probably not what you want here, though you can utilize a repeat loop if you wish to use io.read() via table.insert. However, repeat requires a condition that must be met for it to terminate, such as the length of the table reaching a certain amount (in your example, it would be until (#Table == 4)). Since this is a task you are given, I will not provide an example, but allow you to research this method and use it to your advantage.
Print the values after the process is complete.
You are on the right track with your printing loop. However, it must be noted that iterating through a table always returns two results, an index and a value. In your code, you would only return the index number, so your output would simply return:
1
2
3
4
If you are wanting the actual values, you'll need a placeholder for the index. Oftentimes, the placeholder for an unneeded variable in Lua is the underscore (_). Modify your for loop to account for the index, and you should be set.
Try modifying your code with the suggestions I've given and see if you can figure out how to achieve your end result.
Edited:
Thanks, Piglet, for corrections on the insight! I'd forgotten table itself wasn't a function, and wasn't reserved, but still bad form to use it as a variable name whether local or global. At least, it's how I was taught, but your comment is correct!
I'm adding a string to a table in lua. When I use the table in a function the original table is getting altered. I'm only a beginner but I thought that the function could not do that because it is outside of it's scope. Is there something obvious I'm missing?
local testTable= {}
testTable.name = {}
testTable.name[1] = "Jon"
print(testTable.name[1])
local function testFunc(a)
a.name[1] = "Bob"
end
local newTable = testTable
testFunc(newTable)
print(testTable.name[1])
I expected the output to be:
Jon
Jon
The actual output is:
Jon
Bob
How can the testFunc change the testTable?
You assign testTable's address to newTable, so testTable and newTable point to the same table.
If you want to output be
Jon
Jon
You should copy the table when you assign newTable.
You can copy the table like this function:
function table.copy(old)
local new = {}
for k, v in pairs(old) do
new[k] = v
end
return new
end
When I use the table in a function the original table is getting altered. ... I thought that the function could not do that because it is outside of it's scope.
Local variables have their own scope, but tables do not. Two things to remember:
Variables store references, not values. (This only makes a difference for mutable values.)
Tables are mutable, i.e., they can be changed internally.
Breaking it down:
local newTable = testTable
In this line, you're assigning one variable to another, so both variables refer to the same table.
We mutate a table by assigning to an index within that table, so testFunc alters whatever a (actually a.name) refers to. This is handy, because it allows us to write functions that mutate tables that we pass as arguments.
The following function does nothing, like you would expect, because it assigns a new table to the bare name a (which happens to be a local variable):
local function doNothing(a)
a = {name = {'Bob'}}
end
In lua, now I want to change field name of a table, like
in test1.lua
local t = {
player_id = 2,
item_id = 1,
}
return t
in test2.lua
local t = require "test1"
print( t.item_id )
if I want to change field name item_id -> item_count of t,
I need to use the application like ultraedit, find out all lua file contain item_id, and modified one by one, such modification easy correction or change of leakage, is there any tools can be more easily modified the field name?
If I understand your problem correctly:
(What if item_id also happens to be a field in a different table?)
In my view, there is no generic solution for this task without actually interpreting the script. A field name (e.g., item_id) could appear in many places but be referring to different tables. To make sure you change only references to the correct table you need to actually interpret the script. Given the dynamic nature of Lua scripts, this is not a trivial task.
Using an editor (or preferably a Lua script) to globally replace all occurrences of one name to another will only work if you're certain the 'old' name has only a single context.
A run-time workaround might be to add some metatable to keep both the new and the old name. I think you need to play with the __index and __newindex events. Then, the same field will be accessed by either 'old' or 'new' name.
Example for the metatable trick (only field 'one' is actually part of the table, field 'two' access is made possible via the metatable to read/write field 'one' so that reading from 'two' reads 'one', while writing to 'two' writes to 'one'):
t = {}
t.one = 1
setmetatable(t,{__index = function(t,k)
if k == 'two' then return t.one end
end,
__newindex = function(t,k,v)
if k == 'two' then t.one = v end
end
})
print(t.one,t.two)
t.two = 2
print(t.one,t.two)
Javascript delete keyword deletes a named variable slot from nearest execution environment which it defined.
What's the equivalent in Lua?
var = nil
Environments in Lua are tables, and tables cannot contain nil value - assigning nil to a key in a table effectively deletes that key from the table.
Here is a quote from "Programming in Lua":
Like global variables, table fields
evaluate to nil if they are not
initialized. Also like global
variables, you can assign nil to a
table field to delete it. That is not
a coincidence: Lua stores global
variables in ordinary tables