MCPcopy Create free account
hub / github.com/Serial-Studio/Serial-Studio / forprep

Function forprep

lib/lua/src/lvm.c:218–270  ·  view source on GitHub ↗

** Prepare a numerical for loop (opcode OP_FORPREP). ** Return true to skip the loop. Otherwise, ** after preparation, stack will be as follows: ** ra : internal index (safe copy of the control variable) ** ra + 1 : loop counter (integer loops) or limit (float loops) ** ra + 2 : step ** ra + 3 : control variable */

Source from the content-addressed store, hash-verified

216** ra + 3 : control variable
217*/
218static int forprep (lua_State *L, StkId ra) {
219 TValue *pinit = s2v(ra);
220 TValue *plimit = s2v(ra + 1);
221 TValue *pstep = s2v(ra + 2);
222 if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */
223 lua_Integer init = ivalue(pinit);
224 lua_Integer step = ivalue(pstep);
225 lua_Integer limit;
226 if (step == 0)
227 luaG_runerror(L, "'for' step is zero");
228 setivalue(s2v(ra + 3), init); /* control variable */
229 if (forlimit(L, init, plimit, &limit, step))
230 return 1; /* skip the loop */
231 else { /* prepare loop counter */
232 lua_Unsigned count;
233 if (step > 0) { /* ascending loop? */
234 count = l_castS2U(limit) - l_castS2U(init);
235 if (step != 1) /* avoid division in the too common case */
236 count /= l_castS2U(step);
237 }
238 else { /* step < 0; descending loop */
239 count = l_castS2U(init) - l_castS2U(limit);
240 /* 'step+1' avoids negating 'mininteger' */
241 count /= l_castS2U(-(step + 1)) + 1u;
242 }
243 /* store the counter in place of the limit (which won't be
244 needed anymore) */
245 setivalue(plimit, l_castU2S(count));
246 }
247 }
248 else { /* try making all values floats */
249 lua_Number init; lua_Number limit; lua_Number step;
250 if (l_unlikely(!tonumber(plimit, &limit)))
251 luaG_forerror(L, plimit, "limit");
252 if (l_unlikely(!tonumber(pstep, &step)))
253 luaG_forerror(L, pstep, "step");
254 if (l_unlikely(!tonumber(pinit, &init)))
255 luaG_forerror(L, pinit, "initial value");
256 if (step == 0)
257 luaG_runerror(L, "'for' step is zero");
258 if (luai_numlt(0, step) ? luai_numlt(limit, init)
259 : luai_numlt(init, limit))
260 return 1; /* skip the loop */
261 else {
262 /* make sure internal values are all floats */
263 setfltvalue(plimit, limit);
264 setfltvalue(pstep, step);
265 setfltvalue(s2v(ra), init); /* internal index */
266 setfltvalue(s2v(ra + 3), init); /* control variable */
267 }
268 }
269 return 0;
270}
271
272
273/*

Callers 1

luaV_executeFunction · 0.85

Calls 3

luaG_runerrorFunction · 0.85
forlimitFunction · 0.85
luaG_forerrorFunction · 0.85

Tested by

no test coverage detected