SkittlesAreFalling
SkittlesAreFalling

Reputation: 41

return parameter in lua

format = function(&Return, Length, Format, ...)
    Return = string.format(Format, ...);
    Return = string.sub(Format, 0, Length);
    return 1;
end

local Test;

format(Test, 12, "Hello world %s! This is a test.", "Hello World");

print(Test);

I would love this to print, "Hello world!" without it being returned by the function but being returned by the parameter.

Upvotes: 2

Views: 172

Answers (2)

Oliver
Oliver

Reputation: 29463

In your example, you are not accessing Return, just setting it; also you are not using the returned value '1'. So: why not do this:

format = function(Length, Format, ...)
    local Return = string.format(Format, ...)
    Return = string.sub(Format, 0, Length)
    local status = 1 -- i'm guessing this is a status code of sorts
    return Return, status
end

local Test, stat = format(12, "Hello world %s! This is a test.", "Hello World")

Code review notes:

  • based on the fact that you are using semicolons everywhere and &Return as a function parameter, seems to me you are still "thinking in C". Don't. When you program in Lua, think in Lua. In Lua, you can return multiple values, and there is no need for semicolons, so why clutter the code with unnecessary symbols.
  • I recommend keeping all format components together, plus this way you can easily extend it:

    local Test, stat = format("Hello world %s! This is a test.", 
                             ["Hello World", 12], ['Joe', 5])
    

Upvotes: 1

moteus
moteus

Reputation: 2235

You can do something like

local function Pointer()
  return setmetatable({},{
    __tostring = function(self) return self.value end
  })
end

format = function(Return, Length, Format, ...)
  Return.value = string.sub(Format, 0, Length)
  return 1
end

local Test = Pointer()

format(Test, 12, "Hello world %s! This is a test.", "Hello World")

print(Test)

Upvotes: 6

Related Questions