how to retrieve variable arguments in lua 5.2 [duplicate] - lua

This question already has an answer here:
Parameter implicit "arg" in functions not work in Lua
(1 answer)
Closed 6 years ago.
The reference pages all say things like
function this(...)
end
However when I try to apply the supposed arg variable all I get is a nil reference. Any attempt I've made to capture the arguments results in a nil table. I've tried forcing a local tab = {...} and still get the nil reference. The closest I've managed to get to capturing the arguments is a select("#",...) which only returns the number of arguments. Whenever I try to capture this outside parameter declaration I get nothing but another error...
I've been thoroughly looking into this with no avail... any way I can accomplish this without forcibly passing a table?

The arg argument is for Lua 5.0 only. Since Lua 5.1, the vararg expression ... is used instead.
Try this:
function foo(...)
for k, v in ipairs{...} do
print(k, v)
end
end
foo('hello', 'world')

Related

rails4 AR: Local var is declared in not executed code-block [duplicate]

This question already has answers here:
Confusion with the assignment operation inside a falsy `if` block [duplicate]
(3 answers)
Closed 5 years ago.
In rails 4.2.5: Is it possible, that a locale var will be declared, even if it occurs in a not executed block?
See this example:
class Animal < ActiveRecord::Base
def test
# there is no local var `name`
puts "name " + name.inspect
puts "self.name " + self.name.inspect
if false
name = 'Hund'
end
# now there is a local var `name` (value `nil`)
puts "name " + name.inspect
puts "self.name " + self.name.inspect
end
end
To test it:
>> Animal.new(:name=>'Katze').test
name "Katze"
self.name "Katze"
name nil
self.name "Katze"
We just were very surprised, that name suddenly was nil.
For which reason does it behave like this? Is this wanted behaviour? So we must not rely on name, but using self.name in future?
(No question, one should use self.name = "Hund", but why is that local var declared.)
Thanks and regards, Phil
It's important to realize that when you call self.name you're not actually accessing a variable but rather sending a message to an accessor method
def name
#name
end
It's also important to know how the Ruby parser handles local variables, especially when inside a conditional. This is an excerpt from the Well-Grounded Rubyist Chapter 6.1.2
When the Ruby parser sees the sequence identifier, equal-sign, value,
as in this expression
x = 1
it allocates space for a local variable called x. The creation of the
variable—not the assignment of a value to it, but the internal
creation of a variable—always takes place as a result of this kind of
expression, even if the code isn’t executed! Consider this example:
if false
x = 1
end
p x # Output: nil
p y # Fatal Error: y is unknown
The assignment to x isn’t executed, because it’s wrapped in a failing
conditional test. But the Ruby parser sees the sequence x = 1, from
which it deduces that the program involves a local variable x. The
parser doesn’t care whether x is ever assigned a value. Its job is
just to scour the code for local vari ables for which space needs to
be allocated. The result is that x inhabits a strange kind of variable
limbo. It has been brought into being and initialized to nil. In that
respect, it differs from a variable that has no existence at all; as
you can see in the example, examining x gives you the value nil,
whereas trying to inspect the non-existent variable y results in a
fatal error. But although x exists, it has not played any role in the
program. It exists only as an artifact of the parsing process.
Given the above information, the first time you call name.inpspect in your code, the Ruby parser knows that no such local variable has been defined so it looks to see whether a method by that name exists (it does as it's provided by ActiveRecord) and calls that method - so in the first case name.inspect and self.name.inspect are both calling the same accessor method.
The next time you call name.inspect, you're actually calling the local variable name which the Ruby parser has initialized to nil.
The takeaway is that you should always use self explicitly. Hope this helps. Cheers.
This is a Ruby thing, not a Rails thing.
Ruby does not define a closed scope for if blocks.
You can get more details of the reason here: https://softwareengineering.stackexchange.com/questions/58900/why-if-statements-do-not-introduce-scope-in-ruby-1-9#answer-60413

meaning of * in ruby function [duplicate]

This question already has answers here:
What does the (unary) * operator do in this Ruby code?
(3 answers)
Closed 7 years ago.
I have a basic question about the mearning of * in a function call which I haven't been able to understand from online docs:
def self.new(*args, &block)
What does *args mean in the function call above?
consider a following method
def user(user_name)
puts user_name
end
so when you call
user("RPV")
Output:
RPV
=> nil
but what if you pass more then one argument like
user("RPV", "Marek")
it will give an error
wrong number of arguments (2 for 1)
To avoid this kind of error splat(*) operator is helpful
def user(*user_name)
puts user_name
end
and when you pass more than one argument it handles converts it in array
user("RPV", "Marek")
output:
RPV
Marek
nil
it makes user_name as an array
def user(user_name)
p user_name
end
user("RPV", "Marek")
output:
["RPV", "Marek"]
Hope you got the use of it.
It means you can pass any number of arguments that will be stored in args table inside of this method. Take a look: https://endofline.wordpress.com/2011/01/21/the-strange-ruby-splat/

Meaning of -> shorthand in Ruby [duplicate]

This question already has answers here:
What do you call the -> operator in Ruby?
(3 answers)
Closed 8 years ago.
I was browsing Friendly_id gem code base and I found line with following assignment:
#defaults ||= ->(config) {config.use :reserved}
My questions are:
How do I interpret this line of code?
What does exactly -> do and what does it mean?
Is there any articles about it, how to use it?(Official Ruby documentation would be nice, I haven't found it)
Thank you for your help
This denotes the lambda. With this you are latching an anonymous function which takes a parameter config and computes a block using that variable.
The above expression can also be defined as:
#defaults ||= lambda {|config| config.use :reserved}
Proc is similar to lambda in Ruby, apart from few differences of return and break pattern. Proc can be called as a block saved as an object, while lambda is a method saved as an object. They find their roots in functional programming.
In short, a lambda is a named procedure, which can be saved as an object and can be called later.
inc = ->x{ x + 1 }
inc.call(3)
#=> 4
One common and interesting example of lambda is Rails Scope, where a method is simply assigned in name scope as lambda and can be later used as an action while ActiveRecord querying.

What does absolute sign mean in Ruby?

For example
func(#param) do |f|
some code here
end
and
#param.each do |sth|
some code here
end
What does the absolute value sign do here? I don't understand these two pieces of code.
It's the local variable within the block, so for the line:
#param.each do |sth|
you're iterating over #param right, well each item in #param is referred to singularly as sth.
So if #param refers to an array containing the numbers
[1,3,5,4]
During the first iteration sth will be 1, then 3, then 5, then 4.
Same goes for :
func(#param) do |f|
except now the local variable is called f! You could call it anything you want, even |ihavenoideawhatimdoing|
It's a local variable, it is saying that for the block of code between do...end, the variable f is defined.
It is a parameter to a block. The block is the part of the code between the do and the end. That block of code can use f or sth, which in your examples would probably have been set by func or each.
A tutorial on Ruby blocks will probably be helpful.
Labmda calculus - more abstract, but it was the context in which I first saw these things.
It signifies instance variables. You often see it interchanged if people are using attr_* methods like attr_accessor, which makes #someattr and self.some_attr equivalent in instance methods.

The meaning of `*` when using as a param(not like *arg, just *) [duplicate]

This question already has an answer here:
naked asterisk as parameter in method definition: def f(*)
(1 answer)
Closed 10 years ago.
When I was reading Rails code, I found this
def save(*)
create_or_update || raise(RecordNotSaved)
end
What does the * do? :O
I know what happens when we use it like *args, but in this case, it's just plain *.
ref https://github.com/rails/rails/blob/master/activerecord/lib/active_record/persistence.rb#L119
It means the same thing as it does when used with a parameter name: gobble up all the remaining arguments. Except, since there is no name to bind them to, the arguments are inaccessible. In other words: it takes any number of arguments but ignores them all.
Note that there actually is one way to use the arguments: when you call super without an argument list, the arguments get forwarded as-is to the superclass method.
In this specific case, save doesn't take any arguments. That's what happens with a naked splat. But, as you may be aware, calling save on an ActiveRecord model accepts options because this method gets overridden by ActiveRecord::Validations here:
https://github.com/rails/rails/blob/v3.1.3/activerecord/lib/active_record/validations.rb#L47
# The validation process on save can be skipped by passing <tt>:validate => false</tt>. The regular Base#save method is
# replaced with this when the validations module is mixed in, which it is by default.
def save(options={})
perform_validations(options) ? super : false
end

Resources