lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Lua doesn't allow that syntax, however you can certainly stuff a value in
the callers 'global' environment. Below I create a function 'foo' which
iterates from 1 to 5, then returns nil (using private local 'byteme'). You
call it with the name you want to set in your (current) environment.

---------------------------------
-- create function 'foo' with private variable 'byteme' anonymously

foo = ( function()
  local byteme = 0
  return function (name_to_set_in_caller_env)
    local callers_env = getfenv(2) -- get the caller's 'globals' (environment)
    byteme = byteme + 1
    if byteme > 5 then byteme = nil end
    callers_env[name_to_set_in_caller_env] = byteme
    return byteme
  end
end )()

-- main
x = 0
while foo('x')
do
  print(x)
end
---------------------------------

- Joe



> Greetings, all!  I've just discovered this beautiful language quite
> recently and am having immense fun figuring out how it behaves. :-)
>
> If someone can spare a moment, would it be possible to confirm a
> little detail for me please ...?
>
> Is it the case that the only way to express the *invalid* form:
>
>                  while x = foo() do print(x) end
>
> (in which the focus is on the assignment being performed at the