Ruby on Rails: what does "equals" symbol mean as a parameter? - ruby-on-rails

Some open source I've been using has the below line as a function declaration:
def parse_query(query=nil, options={}, models=nil)
What effect do the "equals" symbols have on the statement? Does it just make the parameters optional?

It sets the default value of the parameter, if the person calling the function does not specify one.

Similar to Python and C++, the equals sign in the parameter list lets you specify a default parameter. For example, in Python:
def hello_world(message="Hello World"):
print "message = "+message
Calling this function like this:
hello_world()
Will result in:
message = Hello World
But calling the function like this:
hello_world("changed default")
results in:
message = changed default

Related

Lua callback function does not work with table

I am trying to change Xadow's baudrate of Uart and trying to do same thing on software PDF but everytime i get errors. I just need to know how should I write the syntax.
Here is the guide of the lua software on xadow's writer
config={}
config["bit"]=9
config["par"]=0
config["stop"]=1
config["bdr"]=9600
function uartData(uart_id,len,data)
print(data)
end
uart_id=uart.create(1,uartData(config))
uart_id = uart.create(port, cb_func [,param])
Param is an optional Lua table as described in the documentation.
You have to call:
uart_id = uart.create(1, uartData, config)
not
uart_id = uart.create(1, uartData(config))
uartData(config) would pass the return value of uartData (nil) to uart.create instead of the function variable uartData
You can simply wirte config.bit=9 instead of config["bit"]=9 btw.

How to determine if sysdig field exists or handle error if it doesn't

I'm using Sysdig to capture some events and have a small chisel (LUA script) to capture and format the events as necessary. On the on_init() I'm requesting fields like so :
f_field = chisel.request_field("<field>")
My question is how can I check if a field exists before requesting it? I'm going to use a new field only just released on 0.24.1 but ideally I'd like my chisel to continue to work on older versions of sysdig without this field. I've tried wrapping the call to chisel.request_field in a pcall() like so :
ok, f_field = pcall(chisel.request_field("<field>"))
and even implementing my own "get_field" function :
function get_field(field)
ok, f = pcall(chisel.request_field(field))
if ok then return f else return nil end
end
f_field = get_field("<field>")
if f_field ~= nil then
-- do something
end
but the error ("chisel requesting nonexistent field <field>") persists.
I can't see a way to check if a field exists but I can't seem to handle the error either. I really don't want multiple versions of my scripts if possible.
Thanks
Steve H
You're almost there. Your issue is in how you're using pcall. Pcall takes a function value and any arguments you wish to call that function with. In your example you're passing the result of the request_field function call to pcall. Try this instead..
ok, f = pcall(chisel.request_field, "field")
pcall will call the chisel method with your args in a protected mode and catch any subsequent errors.

Does Corona SDK or Lua have an 'eval' function available?

I would like to have a dynamic variable name and want to be able to eval and get the value of it and was wondering if this was available. Example on how I want to use it.
audio.play(eval("readAloudPage"..page_num)))
If the value of a global variable is sought, then try _G["readAloudPage"..page_num].
Or define
function eval(name)
return _G[name]
end
Dynamic variable names must be table fields: the globals table which is named _G, or your own table if you don't want to use globals (usually the case). Example:
local yourDynVars = {}
yourDynVars["readAloudPage"..page_num] = ...
audio.play(yourDynVars["readAloudPage"..page_num])
print( yourDynVars.readAloudPage2 ) -- not dynamic; prints nil unless page_num was 2, above
If you replace yourDynVars table by _G the only difference is that in the last line you can access the var directly:
_G["readAloudPage"..page_num] = ...
audio.play(_G["readAloudPage"..page_num])
print( readAloudPage2 ) -- not dynamic; prints nil unless page_num was 2, above
Lua's closest equivalent to eval(code) would be loadstring(code)().
Notice loadstring(code) does not execute the code, it dynamically creates a function with it. Use loadstring(code)() to create and run it.
The closest you can get is lhf's solution to use _G["readAloudPage"..page_num].
Lua provides loadstring function to convert strings to executable functions, but this function is disabled in Corona SDK (and can only be used/accessed in debug environment).

Lua: Interpreting undefined variable by its name

I have a function foo that can get nil values under certain circumstances, i.e. foo(VarA) while VarA is undefined. This undefined VarA should get interpreted as "VarA" but I can't invoke foo("VarA") because VarA should act as an option param (different from normal string params).
mt = {__index = function(t, k) return k end}
setmetatable(_G, mt)
This would get the desired result but now every other undefined variable would return its name. Like abc -> "abc". Do you see any way to only have a metatable active in this specific case? I could switch metatables in my foo method but when I'm in the foo block, the passed param is already nil and its too late.
Appendix: I think the question was not specific enough. Schollii's answer to pass params as a table was good but does not work as intended:
foo({option1 = delete, option2 = push})
This should have the key information (option1 and option2) plus the information of the value (even though delete and push do not exist in global or local namespace). Schollii's approach would give me the key information but not the value information (like "delete" and "push"). I can't define delete and push beforehand because these new "key-words" should get defined by the function itself later on. Passing those new keywords as a string is no option.
It seems like you are developing a domain-specific language within Lua. If that is your intent and you are successful, great. Otherwise, it would be better to stick to more a typical Lua programming style.
Similar to other suggestions:
-- lets the caller decide on the scope of varA
-- and the default string
foo(varA or "varA")
All you need is to test for nil and set VarA's value to its name:
function yourFunc(VarA)
VarA = VarA or "VarA" -- if VarA is nil, it becomes the string "VarA"
... use VarA ...
end
However, you say that VarA should act as an option parameter. I gather you mean that VarA is optional. OK, but Lua does not support named arguments in function calls so if you have
function yourFunc(arg1, arg2, optArg1, optArg2)
...
end
then in order to call yourFunc with optArg2=something, you have to set optArg1 to nil:
yourFunc(1, 2, nil, 3)
In other words you can't do yourFunc(1,2,optArg2=3) which would be pretty neat. But you can get pretty close by having yourFunc accept a table instead of a list of parameters:
function setOptionalArgs(tbl, defaults)
for i,v in ipairs(defaults) do
if tbl[v] == nil then
tbl[v] = v
end
end
for k,v in pairs(defaults) do
if tbl[k] == nil then
tbl[k] = v
end
end
end
function yourFunc(args)
setOptionalArgs(args, {'arg1', arg2=2, 'arg3'})
-- ... use args.arg1, args.arg2 etc ...
print(args.arg1, args.arg2, args.arg3)
end
yourFunc {}
Now you can call
yourFunc {arg1=1}
which will automatically have arg2="arg2". Note that to be clean you should modify setOptionalArgs so only non-array keys get inserted in second loop.

How to skip optional parameters in Lua?

There is a method I have been calling:
t1, t2 = LSL:GetDiffItem(item)
where the method is declared as:
GetDiffID(item, ignoreEnchant, ignoreGem, red, yellow, blue, meta, ignorePris)
Now I want to pass additional parameters, skipping some:
item, ignoreEnchant, ignoreGem, red, yellow, blue, meta, ignorePris
I tried just skipping the parameters:
t1, t2 = LSL:GetDiffItem(item, ignore, ignore, , , , , ignore)
But of course that doesn't work:
unexpected symbol near ','
So, how do I skip optional parameters in Lua?
See also
lua.org - 5.3 - Named Arguments "arguments are positional"
Pass nil. This will be identical to not ever having passed the parameter. However, be aware that the documentation states that you can do this, because most functions will not check each individual optional parameter, and only check each parameter if the previous one was provided.
You could use Named Arguments.
As said on lua.org: "This style of parameter passing is especially helpful when the function has many parameters, and most of them are optional. "
The idea is to pass all arguments as a table:
function InfoItem(item)
if item.name then
print("Name: ",item.name)
end
if item.color then
print("Color: ",item.color)
end
if item.enchant then
print("Enchant: ",item.enchant)
end
if item.specialInfo then
print(item.specialInfo)
end
end
InfoItem{name = "Internet Troll's Bane", color = "silver"}
InfoItem{name = "Death's Toenail Clipper", enchant = "unbreakable", specialInfo = "Little effort required to cut through the thickest nails."}
If you're writing your own functions (rather than using a preexisting API), the method I've used is to pass a table as the only parameter to the function, and fill in the appropriate values in that table. Assigning a metatable with the defaults as the first step in your function avoids looking up defaults at each step, but make sure users know you are overwriting the metatable on their input.
Use nil.
note that this won't work when the C code uses gettop, or relys on 'NONE' such as in a switch/case on the type, or explicity checking for none or nil instead of lua_isnoneornil.

Resources