void _pusharray_wshape(lua_State *L, double *A, const int *shape, int Nd) { int ntot=1; for (int i=0; i<Nd; ++i) ntot *= shape[i]; lunum_pusharray2(L, A, ARRAY_TYPE_DOUBLE, ntot); struct Array *B = lunum_checkarray1(L, -1); array_resize(B, shape, Nd); }
int luaC_array_shape(lua_State *L) // ----------------------------------------------------------------------------- // If there is no argument, return the shape as a table. If the string 'array' // is given, return it as an array. // ----------------------------------------------------------------------------- { struct Array *A = lunum_checkarray1(L, 1); lunum_pusharray2(L, A->shape, ARRAY_TYPE_INT, A->ndims); if (lua_isstring(L, 2)) { if (strcmp(lua_tostring(L, 2), "array") == 0) { return 1; } } lunum_astable(L, 2); lua_replace(L, -2); return 1; }
void _pusharray_i(lua_State *L, int *A, int N) { lunum_pusharray2(L, A, ARRAY_TYPE_INT, N); }
static int luaC_lunum_loadtxt(lua_State *L) // ----------------------------------------------------------------------------- // Opens the text file 'fname' for reading, and parses the data // line-by-line. It is assumed that the data is all floating point, and that // only a space is used as a separator. If there are multiple columns then a 2d // array is created. All rows must have the same number of entries, otherwise an // error is generated. // ----------------------------------------------------------------------------- { const char *fname = luaL_checkstring(L, 1); FILE *input = fopen(fname, "r"); if (input == NULL) { return luaL_error(L, "no such file %s", fname); } size_t nline = 0; size_t ncols = 0; size_t ntot = 0; double *data = NULL; char line[2048]; while (fgets(line, sizeof(line), input)) { if (strlen(line) == 1) { continue; } size_t nvals = 0; double *vals = NULL; char *word = strtok(line, " \n"); while (word) { vals = (double*) realloc(vals, ++nvals*sizeof(double)); vals[nvals-1] = atof(word); word = strtok(NULL, " \n"); } if (ncols == 0) ncols = nvals; if (ncols != nvals) { return luaL_error(L, "wrong number of data on line %d of %s", nline, fname); } data = (double*) realloc(data, (ntot+=nvals)*sizeof(double)); memcpy(data+ntot-nvals, vals, nvals*sizeof(double)); free(vals); ++nline; } fclose(input); lunum_pusharray2(L, data, ARRAY_TYPE_DOUBLE, ntot); Array *A = lunum_checkarray1(L, -1); size_t shape[2] = { nline, ncols }; array_resize_t(A, shape, ncols == 1 ? 1 : 2); free(data); return 1; }