Re: Code Puzzles
Posted: Sun Dec 06, 2015 2:06 pm
I can't claim the last puzzle as mine- it's an Euler project puzzle.
Code: Select all
local a = 10
local b = 15
swap(a,b)
--[[
Output:
Current value of a is 15
Current value of b is 10
]]
So, you're saying thatbartbes wrote:You're probably going for the usual trick of a = a + b, b = a - b, a = a - b, but since lua has no call-by-reference semantics no such function can actually exist. (At least not without going into the debug library.)
Code: Select all
function swap(a,b) a, b = b, a end
No, but this will:zorg wrote:So, you're saying thatbartbes wrote:You're probably going for the usual trick of a = a + b, b = a - b, a = a - b, but since lua has no call-by-reference semantics no such function can actually exist. (At least not without going into the debug library.)won't work?Code: Select all
function swap(a,b) a, b = b, a end
Code: Select all
function swap(a,b) _G.a, _G.b = b, a end
Except a and b are locals, not globals, so sadly that won't work either. The debug library could probably get the two upvalues and then it might be possible though, as bartbes said before.undef wrote:No, but this will:Code: Select all
function swap(a,b) _G.a, _G.b = b, a end
Code: Select all
function swap(a, b)
a = a + b
b = a - b
a = a - b
print("Current value of a is " .. a .. "\nCurrent value of b is " .. b)
end
Why did you give the answerNickRock wrote:I just did thisand worked perfectly fineCode: Select all
function swap(a, b) a = a + b b = a - b a = a - b print("Current value of a is " .. a .. "\nCurrent value of b is " .. b) end
I think you need to give use more information about the problem, I bet this was not presented like this in the euler project.davisdude wrote:I can't claim the last puzzle as mine- it's an Euler project puzzle.
Ah damn I'm sorry, I just wanted to make sure that I didn't make any mistakes explaining the puzzleRanguna259 wrote:Why did you give the answer