Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
Spending Time in Lua — Gideros Forum

Spending Time in Lua

ArtLeeAppsArtLeeApps Member
edited July 2013 in General questions
Hi all,

Can i ask a Lua question please.

I've been reading a book on Lua, and have gone back to this page several times, as it confuses me.
 
function derivative(f,delta) 
    delta=delta or 1e-4 
    return function(x) return ( f(x + delta ) -f(x))/delta
        end
end
 
----- It Runs like this ------------
 
c=derivative(math.sin) print(math.cos(10),c(10))
-->-0.83907152907645-0.83904432662041 Becausefunctionsarefirst-classvaluesinLua,wecanstorethemnoto
My Question :

The part "return function(x) ....."
where is the value of "x" coming from ?
i would expect a value of "x" to be passed to the function....

Comments

  • Accepted Answer
    The entire function
    function(x) return ( f(x + delta ) -f(x))/delta end
    is the return value in this case. So,
    c
    is being set to a version of that function using
    math.sin
    as a base. Notice that in the print call, you're calling
    c(10)
    . So, that 10 is essentially the x for that specific instance of the function. Hope that clears it up a bit. If not, someone will come by with a better explanation. hehe
  • @TheOddLinguist Thank you, that is a bit clearer yes.

    its like defining a function
    myfunc = math.sin(x)
    and calling
    myfunc(100)

    which is the same as math.sin(100)

    but its putting the entire user defined function .... into "c"

    ...i knew i should have been a brick layer.... :)
Sign In or Register to comment.