[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua and pointers
- From: David Given <dg@...>
- Date: Mon, 20 Nov 2006 15:52:35 +0000
Theodor-Iulian Ciobanu wrote:
[...]
> 1) I have a variable whose contents I would like it to be modified by a
> function (would bee foo(&var) in C, with foo declared as foo(var_type*)).
> Can I do this in lua?
No. You can, however, pass in a table, and have the function change the
contents of that table.
function foo(t)
t[1] = t[1] + 1
end
begin
local z = 1
local t = {z}
foo(t)
print(t[1])
end
It's very clumsy, but can work. You may find it easier instead to refactor
your code so that you're returning multiple values (which Lua does very
efficiently and easily).
function add(a, b, c)
a = a + 1
b = b + 1
c = c + 1
return a, b, c
end
begin
local x, y, z = add(1, 2, 3)
end
> 2) str[n] is not the n-th character of str (when str is of course a string).
> Would adding this to the language not be faster than string.sub(str,n,n)
> or would it stray the lua way? (or is there a better way of getting the n-th
> character from a string that I'm missed in the ref manual? I confess to still
> not owning a PiL :oops: )
Possibly, but that's not up to me! However, it's possible to implement this in
pure Lua (on Lua 5.1) using metatable magic:
getmetatable("").__index = function (self, key)
local k = tonumber(key)
if (k ~= nil) then
return string.sub(k, k)
end
return rawget(self, key)
end
(Untested. YMMV.)
(PS. Please line-wrap your posts!)
--
╭─┈David Given┈──McQ─╮ "A line dancer near a graduated cylinder, the
│┈ dg@cowlark.com┈┈┈┈│ blithe spirit inside some wheelbarrow, and a tomato
│┈(dg@tao-group.com)┈│ are what made America great!" --- received via spam
╰─┈www.cowlark.com┈──╯
Attachment:
signature.asc
Description: OpenPGP digital signature