Lua throwaway result - lua

I have a situation where I perform some operations on tables, call them T and V. I have set the metatable up correctly and everything works as expected. The issue is that I usually don't need the result of the calculation. So instead of writing
for i=1,5 do
_=T+V
end
is there a way to just have
for i=1,5 do
T+V
end
?
I am not using the Lua commandline so I cannot just write =T+V.

Make a function that does nothing and pass it to it:
function NOP() end
for i=1,5 do
NOP(T+V)
end
This additionally serves to document your intentions, and that the side-effect is what you're after.

Looking at syntax of Lua in extended BNF I don't see an way to construct an expression (exp) without a equal sign or something else.
There are only 4 cases where an expression (exp) can be used:
Assigning a value e.g. p = exp
As condition e.g. while exp then
In a function call i.e. f(exp)
for indexing i.e. t[exp]

Related

What's the , Lua equivalent of pythons endswith()?

I want to convert this python code to lua .
for i in range(1000,9999):
if str(i).endswith('9'):
print(i)
I've come this far ,,
for var=1000,9000 then
if tostring(var).endswith('9') then
print (var)
end
end
but I don't know what's the lua equivalent of endswith() is ,,, im writing an nmap script,,
working 1st time with lua so pls let me know if there are any errors ,, on my current code .
The python code is not great, you can get the last digit by using modulo %
# python code using modulo
for i in range(1000,9999):
if i % 10 == 9:
print(i)
This also works in Lua. However Lua includes the last number in the loop, unlike python.
-- lua code to do this
for i=1000, 9998 do
if i % 10 == 9 then
print(i)
end
end
However in both languages you could iterate by 10 each time
for i in range(1009, 9999, 10):
print(i)
for i=9, 9998, 10 do
print(i)
for var = 1000, 9000 do
if string.sub(var, -1) == "9" then
-- do your stuff
end
end
XY-Problem
The X problem of how to best port your code to Lua has been answered by quantumpro already, who optimized it & cleaned it up.
I'll focus on your Y problem:
What's the Lua equivalent of Python endswith?
Calling string functions, OOP-style
In Lua, strings have a metatable that indexes the global string library table. String functions are called using str:func(...) in Lua rather than str.func(...) to pass the string str as first "self" argument (see "Difference between . and : in Lua").
Furthermore, if the argument to the call is a single string, you can omit the parentheses, turning str:func("...") into str:func"...".
Constant suffix: Pattern Matching
Lua provides a more powerful pattern matching function that can be used to check whether a string ends with a suffix: string.match. str.endswith("9") in Python is equivalent to str:match"9$" in Lua: $ anchors the pattern at the end of the string and 9 matches the literal character 9.
Be careful though: This approach doesn't work with arbitrary, possibly variable suffices since certain characters - such as $ - are magic characters in Lua patterns and thus have a special meaning. Consider str.endswith("."); this is not equivalent to string:match".$" in Lua, since . matches any character.
I'd say that this is the lua-esque way of checking whether a string ends with a constant suffix. Note that it does not return a boolean, but rather a match (the suffix, a truthy value) if successful or nil (a falsey value) if unsuccessful; it can thus safely be used in ifs. To convert the result into a boolean, you could use not not string:match"9$".
Variable suffix: Rolling your own
Lua's standard library is very minimalistic; as such, you often need to roll your own functions even for basic things. There are two possible implementations for endswith, one using pattern matching and another one using substrings; the latter approach is preferable because it's shorter, possibly faster (Lua uses a naive pattern matching engine) and doesn't have to take care of pattern escaping:
function string:endswith(suffix)
return self:sub(-#suffix) == suffix
end
Explanation: self:sub(-#suffix) returns the last suffix length characters of self, the first argument. This is compared against the suffix.
You can then call this function using the colon (:) syntax:
str = "prefixsuffix"
assert(str:endswith"suffix")
assert(not str:endswith"prefix")

How to invoke Erlang function with variable?

4> abs(1).
1
5> X = abs.
abs
6> X(1).
** exception error: bad function abs
7> erlang:X(1).
1
8>
Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well, for one thing it is just way too much syntactic garbage and makes my eyes bleed. For another thing, I plan on invoking functions out of a list, something like (off the top of my head):
[X(1) || X <- [abs, f1, f2, f3...]].
Attempting to tack on various module names here is going to make the verbosity go through the roof, when the whole point of what I am doing is to reduce verbosity.
EDIT: Look here: http://www.erlangpatterns.org/chain.html The guy has made some pipe-forward function. He is invoking functions the same way I want to above, but his code doesn't work when I try to use it. But from what I know, the guy is an experienced Erlang programmer - I saw him give some keynote or whatever at a conference (well I saw it online).
Did this kind of thing used to work but not anymore? Surely there is a way I can do what I want - invoke these functions without all the verbosity and boilerplate.
EDIT: If I am reading the documentation right, it seems to imply that my example at the top should work (section 8.6) http://erlang.org/doc/reference_manual/expressions.html
I know abs is an atom, not a function. [...] Why does it work when the module name is used?
The documentation explains that (slightly reorganized):
ExprM:ExprF(Expr1,...,ExprN)
each of ExprM and ExprF must be an atom or an expression that
evaluates to an atom. The function is said to be called by using the
fully qualified function name.
ExprF(Expr1,...,ExprN)
ExprF
must be an atom or evaluate to a fun.
If ExprF is an atom the function is said to be called by using the implicitly qualified function name.
When using fully qualified function names, Erlang expects atoms or expression that evaluates to atoms. In other words, you have to bind X to an atom: X = atom. That's exactly what you provide.
But in the second form, Erlang expects either an atom or an expression that evaluates to a function. Notice that last word. In other words, if you do not use fully qualified function name, you have to bind X to a function: X = fun module:function/arity.
In the expression X=abs, abs is not a function but an atom. If you want thus to define a function,you can do so:
D = fun erlang:abs/1.
or so:
X = fun(X)->abs(X) end.
Try:
X = fun(Number) -> abs(Number) end.
Updated:
After looking at the discussion more, it seems like you're wanting to apply multiple functions to some input.
There are two projects that I haven't used personally, but I've starred on Github that may be what you're looking for.
Both of these projects use parse transforms:
fun_chain https://github.com/sasa1977/fun_chain
pipeline https://github.com/stolen/pipeline
Pipeline is unique because it uses a special syntax:
Result = [fun1, mod2:fun2, fun3] (Arg1, Arg2).
Of course, it could also be possible to write your own function to do this using a list of {module, function} tuples and applying the function to the previous output until you get the result.

Getting date parts from a simple treetop parser: wrong argument type Class (expected Module)

For the following treetop grammer, when parsing '3/14/01' (via t = Parser.parse('3/14/01') in irb), I get a "TypeError: wrong argument type Class (expected Module)".
grammar SimpleDate
rule dateMDY
whitespace? month_part ( '/' / '-') day_part ( ('/' / '-') year_part)? whitespace? <DateMDY>
end
rule month_part
( ( '1' [0-2] ) / ( '0'? [1-9] ) ) <MonthLiteral>
end
rule day_part
( ( [12] [0-9] ) / ( '3' [0-1] ) / ( '0'? [1-9] ) ) <DayLiteral>
end
rule year_part
( ( '1' '9' ) / ( '2' [01] ) )? [0-9] [0-9] <YearLiteral> # 1900 through 2199 (4 digit)
end
rule whitespace
[\s]+
end
end
First,
if I comment out the <MonthLiteral> and the <DayLiteral> class references, all is well. Commenting out <DateMDY>, but leaving those Literal objects in, will also issue the error. Commenting out <YearLiteral> does not seem to matter (it'll work or not work regardless) -- that seems to indicate that because the first two are non-terminal, I can't produce elements for them.
There is clearly something I'm not appreciating about how Ruby (or treetop) is instantiating these classes or about AST generation that would explain what happens. Can you explain or point me to something that can help me understand why <MonthLiteral> or <DayLiteral> can't have objects generated?
Second,
this may be a bridge too far, but what I'd really prefer would be to get a DateMDY object with three attributes -- month, day, and year -- so I can readily produce a Ruby Time object from a method to_time in DateMDY, but right now I'd settle for just producing the constituent pieces as objects.
So I tried leaving <DateMDY> as the object and commented out the references to <MonthLiteral>, <DayLiteral>, and <YearLiteral>. I saw that the resulting AST object returned from .parse (t in my original example) has two public methods -- :day_part and :month_part but those seem to be nil when I invoke those (say, puts t.day_part) and there is no :year_part method, so that didn't seem to help me out.
Is it possible to do somehow have DateMDY end up accessing its constituent parts?
FYI, the Parser code itself I'm using is pretty standard stuff from the treetop tutorials and the node_extensions.rb that defines the object classes is also trivial, but I can post those too if you need to see those.
Thanks!
Richard
The error message is telling you exactly what you did wrong. There's only a restricted set of places where you can use a Class this way. When it's allowed, the Class must be a subclass of SyntaxNode. Normally however you should use a Module, which is extend()ed into the SyntaxNode that has been created by an inner rule. The difference in the case of YearLiteral is it does not wrap a parenthesised sequence the way Month and Day literal do. This parenthesised sequence returns an existing SyntaxNode, which cannot be extend()ed with another Class, only with a Module, so you get the TypeError.
As for your second question, the DateMDY object you want should almost certainly not be a SyntaxNode - since all SyntaxNodes retain references to all their child SyntaxNodes and to the input string - this is the parser internals we're talking about. Do you really want to expose bits of the parser internals to the outside world?
Instead, you should arrange for the appropriate syntax node to be visited after the parse has completed, by calling a function that returns your domain object type constructed using the substrings identified and saved by these parser objects. It's best to add these functions to traverse down from your topmost rule, rather than trying to traverse the parse tree "from the outside".
You can do this by adding a block into your top rule, like this (assuming you have an appropriate DateMDY class). When you have a successful parse tree, get your DateMDY by calling "tree.result":
rule dateMDY
whitespace? month_part ( '/' / '-') day_part y:( ('/' / '-') year_part)? whitespace?
{
def result
DateMDY.new(y.empty? ? nil : y.year_part.text_value.to_i,
month_part.text_value.to_i,
day_part.text_value.to_i)
end
}
end
Of course, it's cleaner to add separate result methods for year_part, month_part and day_part; this is just an intro to how to add these methods.

Implementing "cut" in a recursive descent parser

I'm implementing a PEG parser generator in Python, and I've had success so far, except with the "cut" feature, of which whomever knows Prolog must know about.
The idea is that after a cut (!) symbol has been parsed, then no alternative options should be attempted at the same level.
expre = '(' ! list ')' | atom.
Means that after the ( is seen, the parsing must succeed, or fail without trying the second option.
I'm using Python's (very efficient) exception system to force backtracking, so I tried having a special FailedCut exception that would abort the enclosing choice, but that didn't work.
Any pointers to how this functionality is implemented in other parser generators would be helpful.
Maybe the problem I've had has been lack of locality. The code generated for the left part of the rule would be something like:
cut_seen = False
try:
self.token('(')
cut_seen = True
self.call('list')
self.token(')')
except FailedParse as e:
if cut_seen:
raise FailedCut(e)
raise
Then the code generated for the choice (|) operator will skip the following choices if it catches a FailedCut. What I mean by lack of locality is that the choice catching the FailedCut may be deep up in calls, thus having an effect too-difficult to discern.
Instead of making the code generated for sequences try to inform enclosing choices of cuts, I could make the code generated for choices beware of them. That would make the scope of cuts very local, unlike Prolog's, but good enough for what I want in a PEG parser, which is to commit to an option after a certain token sequence has been seen, so the error reporting is refers to that location in the source, instead of to another location where some other option might have been available.
It just occurred to me that if the code generated for a rule/predicate catches FailedCut and translates it into a normal FailedParse exception, then the cuts will have the right scope.
In reference to #false's question, here's a complete example of what I want to work:
start = expre ;
expre = named | term ;
named = word ':' ! term;
term = word ;
In that grammar, word can be reached through named or term, but I would like the parser to commit to the named branch after it has seen the :.
The Solution
To be fair, I've published my work so far at https://bitbucket.org/apalala/grako/.
In the final solution, sequences are enclosed with this context manager:
#contextmanager
def _sequence(self):
self._push_cut()
try:
yield
except FailedParse as e:
if self._cut():
self.error(e, FailedCut)
else:
raise
finally:
self._pop_cut()
And options in a choice function are enclosed with this:
#contextmanager
def _option(self):
p = self._pos
try:
self._push_ast()
try:
yield
ast = self.ast
finally:
self._pop_ast()
self.ast.update(ast)
except FailedCut as e:
self._goto(p)
raise e.nested
except FailedParse:
self._goto(p)
Which forces an exit out of the choice instead of a return to try the next option.
The cuts themselves are implemented thus:
def _cut(self):
self._cut_stack[-1] = True
The full source code may be found on Bitbucket.
In a Prolog with ISO Prolog's exception handling (catch/3 and throw/1), a cut could be implemented as:
cut. % Simply succeeds
cut :-
throw(cut). % on backtracking throws an exception
This would require to catch that exception at appropriate places. For example, each goal (that is non-terminal) of a user defined predicate could now be wrapped with:
catchcut(Goal) :-
catch(Goal,cut,fail).
This is not the most efficient way to implement cut since it does not free resources upon success of !, but it might be sufficient for your purposes. Also, this method now might interfere with user-defined uses of catch/3. But you probably do not want to emulate the entire Prolog language in any case.
Also, consider to use Prolog's dcg-grammars directly. There is a lot of fine print that is not evident when implementing this in another language.
The solution proposed at the end of my question worked:
cut_seen = False
try:
self.token('(')
cut_seen = True
self.call('list')
self.token(')')
except FailedParse as e:
if cut_seen:
raise FailedCut(e)
raise
Then, any time a choice or optional is evaluated, the code looks like this:
p = self.pos
try:
# code for the expression
except FailedCut:
raise
except FailedParse:
self.goto(p)
Edit
The actual solution required keeping a "cut stack". The source code is int Bitbucket.
Just read it.
I'd suggested a deep cut_seen (like with modifying parser's state) and a save and restore state with local variables. This uses the thread's stack as "cut_seen stack".
But you have another solution, and I'm pretty sure you're fine already.
BTW: nice compiler – it's just the opposite of what I'm doing with pyPEG so I can learn alot ;-)

call a function with variable length of arguments

In my lua script I need to call a function which takes an arbritary number of arguments with, well, an arbitrary number of arguments…
I am building up my arguments as a table as I cant know how many arguments there will be.
Sample code:
local result = call.someFunc();
local arguments = {}
for k,v in pairs(result) do
table.insert(arguments, v.name)
end
-- here I would like to somehow pass the whole table and each item in the table
-- is then passed as a single argument to "someOtherFunc"
call.someOtherFunc(arguments[1], arguments[2], arguments[3] ....)
I am pretty new to lua, in PHP e. g. I would use call_user_func_array – is there something similiar in lua?
foo(unpack(arguments)) is equivalent to foo(arguments[1], arguments[2], ...).
The long answer can be found on the Lua Users' Wiki.
This covers everything including trailing nil arguments.
Just pass the table as the argument. No need to split it up into single arguments, just have the function loop through the table.

Resources