Yuescript icon indicating copy to clipboard operation
Yuescript copied to clipboard

Module export outside root block

Open daelvn opened this issue 4 years ago • 1 comments

Trying to use export within a scope (not in root) will throw a compile error. Recently I tried to export a function based on platform, like this:

if IS_WINDOWS
  export isAbsolute = (path) ->
    astring path, "isAbsolute: expected string, got #{type path}"
    return ((":" == path\sub 2, 2) and (DIR_SEP == path\sub 3, 3)) or (DIR_SEP == path\sub 1, 1)
else
  export isAbsolute = (path) ->
    astring path, "isAbsolute: expected string, got #{type path}"
    return (DIR_SEP == path\sub 1, 1)

But I can't use the export keyword like this. I would not like to include the platform check inside the function. Is there any way I could do this?

daelvn avatar Jan 11 '21 11:01 daelvn

The export statement works like an assignment. Using a do block could help, like this:

export isAbsolute = do
  if IS_WINDOWS
    (path) ->
      astring path, "isAbsolute: expected string, got #{type path}"
      return ((":" == path\sub 2, 2) and (DIR_SEP == path\sub 3, 3)) or (DIR_SEP == path\sub 1, 1)
  else
    (path) ->
      astring path, "isAbsolute: expected string, got #{type path}"
      return (DIR_SEP == path\sub 1, 1)

Will be compiled to:

local _module_0 = { }
local isAbsolute
do
  if IS_WINDOWS then
    isAbsolute = function(path)
      astring(path, "isAbsolute: expected string, got " .. tostring(type(path)))
      return ((":" == path:sub(2, 2)) and (DIR_SEP == path:sub(3, 3))) or (DIR_SEP == path:sub(1, 1))
    end
  else
    isAbsolute = function(path)
      astring(path, "isAbsolute: expected string, got " .. tostring(type(path)))
      return (DIR_SEP == path:sub(1, 1))
    end
  end
end
_module_0["isAbsolute"] = isAbsolute
return _module_0

Without do block is OK too.

export isAbsolute = if IS_WINDOWS
  (path) ->
    astring path, "isAbsolute: expected string, got #{type path}"
    return ((":" == path\sub 2, 2) and (DIR_SEP == path\sub 3, 3)) or (DIR_SEP == path\sub 1, 1)
else
  (path) ->
    astring path, "isAbsolute: expected string, got #{type path}"
    return (DIR_SEP == path\sub 1, 1)

pigpigyyy avatar Jan 11 '21 11:01 pigpigyyy