How to write recursive function in MoonScript? - function

Is there something like arguments.callee of JavaScript for MoonScript?

Since Moonscript functions are defined as local func; func = function() end, they are all recursive. This will print 120:
recursive = (n) -> return n > 1 and n*recursive(n-1) or 1
print recursive 5
As far as I know, there is no arguments.calee alternative, but I haven't seen cases where I'd need it either. Even Mozilla's docs say "there are nearly no cases where the same result cannot be achieved with named function expressions" about arguments.callee.

Related

Lua function selector

I have 3 functions. When the user presses the 'E' key I want it to select one of the functions (at random), I feel like it has something to do with math.random but I can't figure it out.
You don't use math.random to select a function; you use it to pick a random number, which you can then use as an index to get the function you need from a table (as one example):
local list = { function() print(1) end, function() print(2) end, function() print(3) end }
math.randomseed(os.time()) -- don't forget to seed or you likely to get the same sequence
for i = 1, 10 do list[math.random(#list)]() end

Mathematica 9 - function definition problems

Please excuse the beginner question. I couldn't find an appropriate answer in any Mathematica tutorial.
I am confused why a definition as a function or a definition in terms of a simple replacement produce different results. Consider this example (Mathematica 9 code):
In[397]:= ClearAll["Global`*"]
In[398]:= Test := 3 c^2 + d^4
In[399]:= v[f_] := D[f, c]
In[400]:= v[Test]
Out[400]= 6 c
The first definition of this simple derivative function "v" acting on a variable is fine. Defining a replacement Test = ... to replace the variable produces the expected result (It derives 3c^2+d^4 with respect to c and answers 6c).
However if I define a function instead of a simple replacement this does not work:
In[401]:= TestFunction[a_, b_] := 3 a^2 + b^4
In[403]:= vFunction[f_[a_, b_]] := D[f[a, b], a]
In[405]:= vFunction[TestFunction[a, b]]
Out[405]= \!\(
\*SubscriptBox[\(\[PartialD]\), \(3\
\*SuperscriptBox[\(a\), \(2\)]\)]\((3\
\*SuperscriptBox[\(a\), \(2\)] +
\*SuperscriptBox[\(b\), \(4\)])\)\)
Why is that? I am risking to look like a moron here, but please enlighten me!
For your convenience, I uploaded a copy of my workbook here
Thanks a lot,
Michael
Do this instead
vFunction[f_,a_,b_]:=D[f[a,b],a];
and when you need derivatives simply use vFunction[TestFunction,a,b] to get it.
When you write down f[x], it means the evaluated value of f with argument value x. So, f[x] is technically not a function anymore. What you want as the argument of vFunction[] is the function TestFunction, not the evaluated value.

Matlab call a function from a function

I have two functions:
function [] = func_one()
S.pb = uicontrol('style','push','unit','pix','posit',[20 20 260 30],
'string','Print Choices','callback',{#func_two,S});
and I have the second function:
function [a] = func_two(varargin)
a = 'alon';
end
I want func_one to return the variable a of func_two. How can I do that please?
I tried:
function [a] = func_one()
But I guess I have to do something with 'callback',{#func_two,S})
Thank you all!
If, as you say, you want func_one to return the value a in func_two then the easiest way to do this without using a callback is:
function [a] = func_one()
S.pb = uicontrol('style','push','unit','pix','posit',[20 20 260 30],
'string','Print Choices');
a = func_two()
The above will allow you to say run a=func_one and a will be the string 'alon'.
If you really really want func_two() to be a callback of your pushbutton, and you want a='alon' to be assigned in the workspace of func_one (the function that calls func_two) then put this in func_two
assignin('caller','a',a)
And if neither is what you want, then maybe you can indicate why you want func_one to return what func_two returns - like the exact interaction you are hoping to have with your GUI and how it differs from what you're actually experiencing.
If you are designing a GUI programmatically, I suggest you use nested functions to share data. Example:
function IncrementExample()
x = 0;
uicontrol('Style','pushbutton', 'String','(0)', ...
'Callback',#callback);
function callback(o,e)
%# you can access the variable x in here
x = x + 1;
%# update button text
set(o, 'String',sprintf('(%d)',x))
drawnow
end
end

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.

Passing variables into a function in Lua

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
If I try to call that function like this:
local test = slideView.new( myImages )
test.jumpToImage(2)
I get this error:
attempt to compare number with nil
at line 225. It would seem that "num" is not getting passed into the function. Why is this?
Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.
You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)
Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's : syntax.