lua-users home
lua-l archive

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




2016-04-19 14:15 GMT+02:00 Soni L. <fakedme@gmail.com>:


On 19/04/16 08:45 AM, Luiz Henrique de Figueiredo wrote:
I see. This is the only one point i assume, was the wrong design
decision: Omit the explicit statement delimitter ";"
If you want this in your version of Lua, you could add a token filter
that replaces '; .' with '; self.' and the same for `:`.

See http://lua-users.org/lists/lua-l/2008-01/msg00524.html for a similar
but simpler solution to the same problem of avoiding writting 'self'.

Alternatively[1]:

local function with(t, e)
  return setmetatable({}, {__index=function(t,k) return t[k] or e[k] end, __newindex = t})
end


do local _ENV = with(self, _ENV)
  -- do stuff that relies on the internal environment here, all assignments are done on self and _ENV is used as a fallback.
  f(x) -- basically self.f(self.x)
  f(self) -- self is a local, so it doesn't pull from self
  f(with) -- with is a local, so it doesn't pull from self
  print("test") -- prints "test" unless `self.print` exists
  -- etc
end
-- do stuff that relies on the external environment here

[1] - Inspired by http://lua-users.org/lists/lua-l/2016-03/msg00080.html

--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.




If you let your methods return "self", you can do the : method call thing, it's sometimes used like this:

struct "my_struct"
 : int "x"
 : int "y"
 : string "name

In this example, "struct" is a function returning the struct object and its member functions "int" and "string" that declare variables return the same object. 

However I don't find that writing "self" before a function call or such a thing is wasting my time. And as Soni wrote, you can use the environment table to quick access values (albeit, when doing a function call, you'll have to pass "self" as first argument anyway, therefore it only safes you from writing ":"). 
As for field access, I'd assign often used members to variables instead


local x,y = self.x, self.y