lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


In Lua I can define two functions that share state through a closure:

function newf(state)
   local function a()
      -- do something with state
  end
  local function b()
     -- do something with state
  end
   return a, b
end

a, b = newf(state)

Can I do this in C? How?

The reason I ask is that, in my environment I don't have access to the normal srand and rand functions in the C library. What I have is a random-number generator function (only callable from C) that takes its seed as an argument and updates the seed for the next call, like this:

long seed, r;

r = myrand(&seed);

I'd like to use this function to generate random numbers, but define two functions, callable from Lua, to maintain the seed. The first function would act like srand and set the seed, the second function would act like rand, calling the random number generator and, upon its return, updating the seed for the next call.