Add use
keyword
#94
Replies: 2 comments
-
The Lua way to do this would be to set a local |
Beta Was this translation helpful? Give feedback.
-
The language does not have this in its core and there is little motivation for that right now. However is in the language goals to give means to implement such feature with some meta programming, this doable right now using the preprocessor, here is an example of that feature implemented: -- Code to implement `using` macro.
##[[
local visitors = require 'nelua.analyzer'.visitors
local orig_visitors_Id = visitors.Id
-- Hook Id AST node visitor.
function visitors.Id(context, node)
local name = node[1]
if scope.usingfields then -- the scope has 'using' fields
local usingsymbol = scope.usingfields[name] -- get symbol for the using field
if usingsymbol and -- found a using field
not context.scope.symbols[name] then -- no local with the same name
-- transform this 'Id' node to 'DotIndex' node
local newnode = aster.DotIndex{name, aster.Id{usingsymbol.name}}
return context:transform_and_traverse_node(node, newnode)
end
end
-- run the original Id visitor
return orig_visitors_Id(context, node)
end
-- Using macro
function using(symbol)
local scope = context.scope -- get current scope
scope.usingfields = scope.usingfields or {} -- create using fields table
for _,field in ipairs(symbol.type.fields) do
scope.usingfields[field.name] = symbol -- associate a field with a symbol
end
end
]]
local Config = @record {
vsync: boolean,
resizable: boolean,
}
local function run(conf: Config)
## using(conf)
if vsync then
print('vsync is on')
elseif resizable then
print('resizable is on')
end
end
local conf: Config = {vsync = true}
run(conf) There you have, the require 'using'
local Config = @record {
vsync: boolean,
resizable: boolean,
}
local function run(conf: Config)
## using(conf)
if vsync then
print('vsync is on')
elseif resizable then
print('resizable is on')
end
end
local conf: Config = {vsync = true}
run(conf) |
Beta Was this translation helpful? Give feedback.
-
hello @edubart
i think the
use
would be usefulexample:
Beta Was this translation helpful? Give feedback.
All reactions