|
284 | 284 | -- | Interpreter | -- |
285 | 285 | -- =========================================== -- |
286 | 286 |
|
| 287 | +local Stack = {} |
| 288 | + |
| 289 | +--[[ |
| 290 | + Puts the given value onto the stack. |
| 291 | +--]] |
| 292 | +function Stack:push(value) |
| 293 | + self._content[self.size + 1] = value |
| 294 | + self.size = self.size + 1 |
| 295 | +end |
| 296 | + |
| 297 | +--[[ |
| 298 | + Removes the top value of the stack and returns it. |
| 299 | +
|
| 300 | + If there is no value on the stack, it returns nil. |
| 301 | +--]] |
| 302 | +function Stack:pop() |
| 303 | + if self.size == 0 then |
| 304 | + return nil |
| 305 | + end |
| 306 | + |
| 307 | + self.size = self.size - 1 |
| 308 | + return self._content[self.size + 1] |
| 309 | +end |
| 310 | + |
| 311 | +--[[ |
| 312 | + Returns the top value on the stack, but does not remove it. |
| 313 | +
|
| 314 | + If there is no value on the stack, it returns nil. |
| 315 | +--]] |
| 316 | +function Stack:peek() |
| 317 | + if self.size == 0 then |
| 318 | + return nil |
| 319 | + end |
| 320 | + |
| 321 | + return self._content[self.size] |
| 322 | +end |
| 323 | + |
| 324 | +--[[ |
| 325 | + Gives the value on the stack with the index. |
| 326 | +
|
| 327 | + Given the scenario: |
| 328 | + ``` |
| 329 | + stack:push("Hola") |
| 330 | + stack:push("Hi") |
| 331 | + stack:push("Hallo") |
| 332 | + stack:push("Bonjour") |
| 333 | +
|
| 334 | + print(stack:get(1)) -- Prints "Hola" |
| 335 | + print(stack:get(3)) -- Prints "Hallo" |
| 336 | + print(stack:get(2)) -- Prints "Hi" |
| 337 | + print(stack:get(4)) -- Prints "Bonjour" |
| 338 | + ``` |
| 339 | +
|
| 340 | + If the index is invalid, it will returns a nil: |
| 341 | + ``` |
| 342 | + stack -- Currently has no elements |
| 343 | + if stack:get(1) == nil then |
| 344 | + print("Nothing here") -- Prints |
| 345 | + end |
| 346 | +
|
| 347 | + stack:get(-10) -- Also returns nil |
| 348 | + ``` |
| 349 | +--]] |
| 350 | +function Stack:get(index) |
| 351 | + if index < 0 or index > self.size then |
| 352 | + return nil |
| 353 | + end |
| 354 | + |
| 355 | + return self._content[index] |
| 356 | +end |
| 357 | + |
| 358 | +--[[ |
| 359 | + Returns a stack datastructure. |
| 360 | + A stack is a LIFO (Last in, first out) datastructure where the last element that |
| 361 | + was added, will be the first that can be removed. |
| 362 | +--]] |
| 363 | +function LuASM.stack() |
| 364 | + local obj = { -- No size limit as this can be implemented if necessary |
| 365 | + _content = {}, |
| 366 | + size = 0, |
| 367 | + } |
| 368 | + |
| 369 | + setmetatable(obj, Stack) |
| 370 | + Stack.__index = Stack |
| 371 | + |
| 372 | + return obj |
| 373 | +end |
| 374 | + |
287 | 375 | local interpreter = {} |
288 | 376 | function LuASM:interpreter() |
289 | 377 | local obj = {} |
|
0 commit comments